1 ;;; python.el --- Python's flying circus support for Emacs
3 ;; Copyright (C) 2003-2013 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. As an alternative you can use the defined
159 ;; skeleton commands: `python-skeleton-class', `python-skeleton-def'
160 ;; `python-skeleton-for', `python-skeleton-if', `python-skeleton-try'
161 ;; and `python-skeleton-while'.
163 ;; FFAP: You can find the filename for a given module when using ffap
164 ;; out of the box. This feature needs an inferior python shell
167 ;; Code check: Check the current file for errors with `python-check'
168 ;; using the program defined in `python-check-command'.
170 ;; Eldoc: returns documentation for object at point by using the
171 ;; inferior python subprocess to inspect its documentation. As you
172 ;; might guessed you should run `python-shell-send-buffer' from time
173 ;; to time to get better results too.
175 ;; Imenu: This mode supports Imenu in its most basic form, letting it
176 ;; build the necessary alist via `imenu-default-create-index-function'
177 ;; by having set `imenu-extract-index-name-function' to
178 ;; `python-info-current-defun' and
179 ;; `imenu-prev-index-position-function' to
180 ;; `python-imenu-prev-index-position'.
182 ;; If you used python-mode.el you probably will miss auto-indentation
183 ;; when inserting newlines. To achieve the same behavior you have
186 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
188 ;; 2) Add the following hook in your .emacs:
190 ;; (add-hook 'python-mode-hook
192 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
194 ;; I'd recommend the first one since you'll get the same behavior for
195 ;; all modes out-of-the-box.
199 ;; Add this to your .emacs:
201 ;; (add-to-list 'load-path "/folder/containing/file")
208 (require 'ansi-color
)
211 ;; Avoid compiler warnings
212 (defvar view-return-to-alist
)
213 (defvar compilation-error-regexp-alist
)
214 (defvar outline-heading-end-regexp
)
216 (autoload 'comint-mode
"comint")
219 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
221 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python") 'python-mode
))
224 "Python Language's flying circus support for Emacs."
227 :link
'(emacs-commentary-link "python"))
232 (defvar python-mode-map
233 (let ((map (make-sparse-keymap)))
235 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
236 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
237 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
238 (define-key map
"\C-c\C-j" 'imenu
)
240 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
241 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
242 (define-key map
"\C-c<" 'python-indent-shift-left
)
243 (define-key map
"\C-c>" 'python-indent-shift-right
)
244 (define-key map
":" 'python-indent-electric-colon
)
246 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
247 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
248 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
249 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
250 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
251 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
253 (define-key map
"\C-c\C-p" 'run-python
)
254 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
255 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
256 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
257 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
258 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
259 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
260 ;; Some util commands
261 (define-key map
"\C-c\C-v" 'python-check
)
262 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
264 (substitute-key-definition 'complete-symbol
'completion-at-point
266 (easy-menu-define python-menu map
"Python Mode menu"
268 :help
"Python-specific Features"
269 ["Shift region left" python-indent-shift-left
:active mark-active
270 :help
"Shift region left by a single indentation step"]
271 ["Shift region right" python-indent-shift-right
:active mark-active
272 :help
"Shift region right by a single indentation step"]
274 ["Start of def/class" beginning-of-defun
275 :help
"Go to start of outermost definition around point"]
276 ["End of def/class" end-of-defun
277 :help
"Go to end of definition around point"]
278 ["Mark def/class" mark-defun
279 :help
"Mark outermost definition around point"]
280 ["Jump to def/class" imenu
281 :help
"Jump to a class or function definition"]
285 ["Start interpreter" run-python
286 :help
"Run inferior Python process in a separate buffer"]
287 ["Switch to shell" python-shell-switch-to-shell
288 :help
"Switch to running inferior Python process"]
289 ["Eval string" python-shell-send-string
290 :help
"Eval string in inferior Python session"]
291 ["Eval buffer" python-shell-send-buffer
292 :help
"Eval buffer in inferior Python session"]
293 ["Eval region" python-shell-send-region
294 :help
"Eval region in inferior Python session"]
295 ["Eval defun" python-shell-send-defun
296 :help
"Eval defun in inferior Python session"]
297 ["Eval file" python-shell-send-file
298 :help
"Eval file in inferior Python session"]
299 ["Debugger" pdb
:help
"Run pdb under GUD"]
301 ["Check file" python-check
302 :help
"Check file for errors"]
303 ["Help on symbol" python-eldoc-at-point
304 :help
"Get help on symbol at point"]
305 ["Complete symbol" completion-at-point
306 :help
"Complete symbol before point"]))
308 "Keymap for `python-mode'.")
311 ;;; Python specialized rx
314 (defconst python-rx-constituents
315 `((block-start .
,(rx symbol-start
316 (or "def" "class" "if" "elif" "else" "try"
317 "except" "finally" "for" "while" "with")
319 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
321 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
322 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
323 (+ space
) "==" (+ space
)
324 (any ?
' ?
\") "__main__" (any ?
' ?
\")
326 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
327 (open-paren .
,(rx (or "{" "[" "(")))
328 (close-paren .
,(rx (or "}" "]" ")")))
329 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
330 ;; FIXME: rx should support (not simple-operator).
331 (not-simple-operator .
,(rx
333 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
334 ;; FIXME: Use regexp-opt.
335 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
336 "=" "%" "**" "//" "<<" ">>" "<=" "!="
337 "==" ">=" "is" "not")))
338 ;; FIXME: Use regexp-opt.
339 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
340 ">>=" "<<=" "&=" "^=" "|=")))
341 (string-delimiter .
,(rx (and
342 ;; Match even number of backslashes.
343 (or (not (any ?
\\ ?
\' ?
\")) point
344 ;; Quotes might be preceded by a escaped quote.
345 (and (or (not (any ?
\\)) point
) ?
\\
346 (* ?
\\ ?
\\) (any ?
\' ?
\")))
348 ;; Match single or triple quotes of any kind.
349 (group (or "\"" "\"\"\"" "'" "'''"))))))
350 "Additional Python specific sexps for `python-rx'")
352 (defmacro python-rx
(&rest regexps
)
353 "Python mode specialized rx macro.
354 This variant of `rx' supports common python named REGEXPS."
355 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
356 (cond ((null regexps
)
359 (rx-to-string `(and ,@regexps
) t
))
361 (rx-to-string (car regexps
) t
))))))
364 ;;; Font-lock and syntax
366 (defun python-syntax-context (type &optional syntax-ppss
)
367 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
368 TYPE can be `comment', `string' or `paren'. It returns the start
369 character address of the specified TYPE."
370 (declare (compiler-macro
374 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
375 (and (nth 4 ppss
) (nth 8 ppss
))))
377 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
378 (and (nth 3 ppss
) (nth 8 ppss
))))
380 `(nth 1 (or ,syntax-ppss
(syntax-ppss))))
382 (let ((ppss (or syntax-ppss
(syntax-ppss))))
384 (`comment
(and (nth 4 ppss
) (nth 8 ppss
)))
385 (`string
(and (nth 3 ppss
) (nth 8 ppss
)))
386 (`paren
(nth 1 ppss
))
389 (defun python-syntax-context-type (&optional syntax-ppss
)
390 "Return the context type using SYNTAX-PPSS.
391 The type returned can be `comment', `string' or `paren'."
392 (let ((ppss (or syntax-ppss
(syntax-ppss))))
394 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
395 ((nth 1 ppss
) 'paren
))))
397 (defsubst python-syntax-comment-or-string-p
()
398 "Return non-nil if point is inside 'comment or 'string."
399 (nth 8 (syntax-ppss)))
401 (define-obsolete-function-alias
402 'python-info-ppss-context
#'python-syntax-context
"24.3")
404 (define-obsolete-function-alias
405 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
407 (define-obsolete-function-alias
408 'python-info-ppss-comment-or-string-p
409 #'python-syntax-comment-or-string-p
"24.3")
411 (defvar python-font-lock-keywords
415 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
416 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
417 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
422 ;; False, None, and True are listed as keywords on the Python 3
423 ;; documentation, but since they also qualify as constants they are
424 ;; fontified like that in order to keep font-lock consistent between
431 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
432 (1 font-lock-function-name-face
))
434 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
435 (1 font-lock-type-face
))
439 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
440 ;; copyright, license, credits, quit and exit are added by the site
441 ;; module and they are not intended to be used in programs
442 "copyright" "credits" "exit" "license" "quit")
443 symbol-end
) . font-lock-constant-face
)
445 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
446 (0+ "." (1+ (or word ?_
)))))
447 (1 font-lock-type-face
))
448 ;; Builtin Exceptions
451 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
452 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
453 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
454 "ImportError" "ImportWarning" "IndexError" "KeyError"
455 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
456 "NotImplementedError" "OSError" "OverflowError"
457 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
458 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
459 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
460 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
461 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
462 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
466 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
468 symbol-end
) . font-lock-type-face
)
472 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
473 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
474 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
475 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
476 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
477 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
478 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
479 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
482 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
483 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
486 "ascii" "bytearray" "bytes" "exec"
488 "__all__" "__doc__" "__name__" "__package__")
489 symbol-end
) . font-lock-builtin-face
)
491 ;; support for a = b = c = 5
493 (let ((re (python-rx (group (+ (any word ?. ?_
)))
494 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
495 assignment-operator
)))
496 (when (re-search-forward re limit t
)
497 (while (and (python-syntax-context 'paren
)
498 (re-search-forward re limit t
)))
499 (if (not (or (python-syntax-context 'paren
)
500 (equal (char-after (point-marker)) ?
=)))
502 (set-match-data nil
)))))
503 (1 font-lock-variable-name-face nil nil
))
504 ;; support for a, b, c = (1, 2, 3)
506 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
507 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
508 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
509 assignment-operator
)))
510 (when (and (re-search-forward re limit t
)
511 (goto-char (nth 3 (match-data))))
512 (while (and (python-syntax-context 'paren
)
513 (re-search-forward re limit t
))
514 (goto-char (nth 3 (match-data))))
515 (if (not (python-syntax-context 'paren
))
517 (set-match-data nil
)))))
518 (1 font-lock-variable-name-face nil nil
))))
520 (defconst python-syntax-propertize-function
521 (syntax-propertize-rules
522 ((python-rx string-delimiter
)
523 (0 (ignore (python-syntax-stringify))))))
525 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
526 "Count number of quotes around point (max is 3).
527 QUOTE-CHAR is the quote char to count. Optional argument POINT is
528 the point where scan starts (defaults to current point) and LIMIT
529 is used to limit the scan."
532 (or (not limit
) (< (+ point i
) limit
))
533 (eq (char-after (+ point i
)) quote-char
))
537 (defun python-syntax-stringify ()
538 "Put `syntax-table' property correctly on single/triple quotes."
539 (let* ((num-quotes (length (match-string-no-properties 1)))
541 (backward-char num-quotes
)
543 (forward-char num-quotes
)))
544 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
545 (quote-starting-pos (- (point) num-quotes
))
546 (quote-ending-pos (point))
549 (python-syntax-count-quotes
550 (char-before) string-start quote-starting-pos
))))
551 (cond ((and string-start
(= num-closing-quotes
0))
552 ;; This set of quotes doesn't match the string starting
556 ;; This set of quotes delimit the start of a string.
557 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
558 'syntax-table
(string-to-syntax "|")))
559 ((= num-quotes num-closing-quotes
)
560 ;; This set of quotes delimit the end of a string.
561 (put-text-property (1- quote-ending-pos
) quote-ending-pos
562 'syntax-table
(string-to-syntax "|")))
563 ((> num-quotes num-closing-quotes
)
564 ;; This may only happen whenever a triple quote is closing
565 ;; a single quoted string. Add string delimiter syntax to
567 (put-text-property quote-starting-pos quote-ending-pos
568 'syntax-table
(string-to-syntax "|"))))))
570 (defvar python-mode-syntax-table
571 (let ((table (make-syntax-table)))
572 ;; Give punctuation syntax to ASCII that normally has symbol
573 ;; syntax or has word syntax and isn't a letter.
574 (let ((symbol (string-to-syntax "_"))
575 (sst (standard-syntax-table)))
578 (if (equal symbol
(aref sst i
))
579 (modify-syntax-entry i
"." table
)))))
580 (modify-syntax-entry ?$
"." table
)
581 (modify-syntax-entry ?%
"." table
)
583 (modify-syntax-entry ?
# "<" table
)
584 (modify-syntax-entry ?
\n ">" table
)
585 (modify-syntax-entry ?
' "\"" table
)
586 (modify-syntax-entry ?
` "$" table
)
588 "Syntax table for Python files.")
590 (defvar python-dotty-syntax-table
591 (let ((table (make-syntax-table python-mode-syntax-table
)))
592 (modify-syntax-entry ?.
"w" table
)
593 (modify-syntax-entry ?_
"w" table
)
595 "Dotty syntax table for Python files.
596 It makes underscores and dots word constituent chars.")
601 (defcustom python-indent-offset
4
602 "Default indentation offset for Python."
607 (defcustom python-indent-guess-indent-offset t
608 "Non-nil tells Python mode to guess `python-indent-offset' value."
613 (defcustom python-indent-trigger-commands
614 '(indent-for-tab-command yas-expand yas
/expand
)
615 "Commands that might trigger a `python-indent-line' call."
616 :type
'(repeat symbol
)
619 (define-obsolete-variable-alias
620 'python-indent
'python-indent-offset
"24.3")
622 (define-obsolete-variable-alias
623 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
625 (defvar python-indent-current-level
0
626 "Current indentation level `python-indent-line-function' is using.")
628 (defvar python-indent-levels
'(0)
629 "Levels of indentation available for `python-indent-line-function'.")
631 (defvar python-indent-dedenters
'("else" "elif" "except" "finally")
632 "List of words that should be dedented.
633 These make `python-indent-calculate-indentation' subtract the value of
634 `python-indent-offset'.")
636 (defun python-indent-guess-indent-offset ()
637 "Guess and set `python-indent-offset' for the current buffer."
642 (goto-char (point-min))
644 (while (and (not block-end
)
646 (python-rx line-start block-start
) nil t
))
648 (not (python-syntax-context-type))
650 (goto-char (line-end-position))
651 (python-util-forward-comment -
1)
652 (if (equal (char-before) ?
:)
655 (when (python-info-block-continuation-line-p)
656 (while (and (python-info-continuation-line-p)
659 (python-util-forward-comment -
1)
660 (when (equal (char-before) ?
:)
662 (setq block-end
(point-marker))))
665 (goto-char block-end
)
666 (python-util-forward-comment)
667 (current-indentation))))
669 (set (make-local-variable 'python-indent-offset
) indentation
)
670 (message "Can't guess python-indent-offset, using defaults: %s"
671 python-indent-offset
)))))))
673 (defun python-indent-context ()
674 "Get information on indentation context.
675 Context information is returned with a cons with the form:
678 Where status can be any of the following symbols:
679 * inside-paren: If point in between (), {} or []
680 * inside-string: If point is inside a string
681 * after-backslash: Previous line ends in a backslash
682 * after-beginning-of-block: Point is after beginning of block
683 * after-line: Point is after normal line
684 * no-indent: Point is at beginning of buffer or other special case
685 START is the buffer position where the sexp starts."
688 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
692 ;; Beginning of buffer
694 (goto-char (line-beginning-position))
698 ((setq start
(python-syntax-context 'string ppss
))
701 ((setq start
(python-syntax-context 'paren ppss
))
704 ((setq start
(when (not (or (python-syntax-context 'string ppss
)
705 (python-syntax-context 'comment ppss
)))
706 (let ((line-beg-pos (line-beginning-position)))
707 (when (python-info-line-ends-backslash-p
709 (- line-beg-pos
2)))))
711 ;; After beginning of block
712 ((setq start
(save-excursion
714 (back-to-indentation)
715 (python-util-forward-comment -
1)
716 (equal (char-before) ?
:))
717 ;; Move to the first block start that's not in within
718 ;; a string, comment or paren and that's not a
719 ;; continuation line.
720 (while (and (re-search-backward
721 (python-rx block-start
) nil t
)
723 (python-syntax-context-type)
724 (python-info-continuation-line-p))))
725 (when (looking-at (python-rx block-start
))
727 'after-beginning-of-block
)
729 ((setq start
(save-excursion
730 (back-to-indentation)
731 (skip-chars-backward (rx (or whitespace ?
\n)))
732 (python-nav-beginning-of-statement)
739 (defun python-indent-calculate-indentation ()
740 "Calculate correct indentation offset for the current line."
741 (let* ((indentation-context (python-indent-context))
742 (context-status (car indentation-context
))
743 (context-start (cdr indentation-context
)))
747 (pcase context-status
749 ;; When point is after beginning of block just add one level
750 ;; of indentation relative to the context-start
751 (`after-beginning-of-block
752 (goto-char context-start
)
753 (+ (current-indentation) python-indent-offset
))
754 ;; When after a simple line just use previous line
755 ;; indentation, in the case current line starts with a
756 ;; `python-indent-dedenters' de-indent one level.
760 (goto-char context-start
)
761 (current-indentation))
763 (back-to-indentation)
764 (looking-at (regexp-opt python-indent-dedenters
)))
767 ;; When inside of a string, do nothing. just use the current
768 ;; indentation. XXX: perhaps it would be a good idea to
769 ;; invoke standard text indentation here
771 (goto-char context-start
)
772 (current-indentation))
773 ;; After backslash we have several possibilities.
776 ;; Check if current line is a dot continuation. For this
777 ;; the current line must start with a dot and previous
778 ;; line must contain a dot too.
780 (back-to-indentation)
781 (when (looking-at "\\.")
782 ;; If after moving one line back point is inside a paren it
783 ;; needs to move back until it's not anymore
787 (python-syntax-context 'paren
))))
788 (goto-char (line-end-position))
789 (while (and (re-search-backward
790 "\\." (line-beginning-position) t
)
791 (python-syntax-context-type)))
792 (if (and (looking-at "\\.")
793 (not (python-syntax-context-type)))
794 ;; The indentation is the same column of the
795 ;; first matching dot that's not inside a
796 ;; comment, a string or a paren
798 ;; No dot found on previous line, just add another
799 ;; indentation level.
800 (+ (current-indentation) python-indent-offset
)))))
801 ;; Check if prev line is a block continuation
802 ((let ((block-continuation-start
803 (python-info-block-continuation-line-p)))
804 (when block-continuation-start
805 ;; If block-continuation-start is set jump to that
806 ;; marker and use first column after the block start
807 ;; as indentation value.
808 (goto-char block-continuation-start
)
810 (python-rx block-start
(* space
))
811 (line-end-position) t
)
813 ;; Check if current line is an assignment continuation
814 ((let ((assignment-continuation-start
815 (python-info-assignment-continuation-line-p)))
816 (when assignment-continuation-start
817 ;; If assignment-continuation is set jump to that
818 ;; marker and use first column after the assignment
819 ;; operator as indentation value.
820 (goto-char assignment-continuation-start
)
824 (goto-char (python-info-beginning-of-backslash))
829 (or (python-info-beginning-of-backslash) (point)))
830 (python-info-line-ends-backslash-p)))
831 ;; The two previous lines ended in a backslash so we must
832 ;; respect previous line indentation.
833 (current-indentation)
834 ;; What happens here is that we are dealing with the second
835 ;; line of a backslash continuation, in that case we just going
836 ;; to add one indentation level.
837 (+ (current-indentation) python-indent-offset
)))))
838 ;; When inside a paren there's a need to handle nesting
842 ;; If current line closes the outermost open paren use the
843 ;; current indentation of the context-start line.
845 (skip-syntax-forward "\s" (line-end-position))
846 (when (and (looking-at (regexp-opt '(")" "]" "}")))
849 (not (python-syntax-context 'paren
))))
850 (goto-char context-start
)
851 (current-indentation))))
852 ;; If open paren is contained on a line by itself add another
853 ;; indentation level, else look for the first word after the
854 ;; opening paren and use it's column position as indentation
856 ((let* ((content-starts-in-newline)
859 (if (setq content-starts-in-newline
861 (goto-char context-start
)
865 (line-beginning-position)
867 (python-util-forward-comment))
869 (+ (current-indentation) python-indent-offset
)
873 ;; If current line closes a nested open paren de-indent one
876 (back-to-indentation)
877 (looking-at (regexp-opt '(")" "]" "}"))))
878 (- indent python-indent-offset
))
879 ;; If the line of the opening paren that wraps the current
880 ;; line starts a block add another level of indentation to
881 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
883 (when (and content-starts-in-newline
885 (goto-char context-start
)
886 (back-to-indentation)
887 (looking-at (python-rx block-start
))))
888 (+ indent python-indent-offset
))))
891 (defun python-indent-calculate-levels ()
892 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
893 (let* ((indentation (python-indent-calculate-indentation))
894 (remainder (% indentation python-indent-offset
))
895 (steps (/ (- indentation remainder
) python-indent-offset
)))
896 (setq python-indent-levels
(list 0))
897 (dotimes (step steps
)
898 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
899 (when (not (eq 0 remainder
))
900 (push (+ (* python-indent-offset steps
) remainder
) python-indent-levels
))
901 (setq python-indent-levels
(nreverse python-indent-levels
))
902 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
904 (defun python-indent-toggle-levels ()
905 "Toggle `python-indent-current-level' over `python-indent-levels'."
906 (setq python-indent-current-level
(1- python-indent-current-level
))
907 (when (< python-indent-current-level
0)
908 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
910 (defun python-indent-line (&optional force-toggle
)
911 "Internal implementation of `python-indent-line-function'.
912 Uses the offset calculated in
913 `python-indent-calculate-indentation' and available levels
914 indicated by the variable `python-indent-levels' to set the
917 When the variable `last-command' is equal to one of the symbols
918 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
919 non-nil it cycles levels indicated in the variable
920 `python-indent-levels' by setting the current level in the
921 variable `python-indent-current-level'.
923 When the variable `last-command' is not equal to one of the
924 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
925 is nil it calculates possible indentation levels and saves it in
926 the variable `python-indent-levels'. Afterwards it sets the
927 variable `python-indent-current-level' correctly so offset is
928 equal to (`nth' `python-indent-current-level'
929 `python-indent-levels')"
931 (and (or (and (memq this-command python-indent-trigger-commands
)
932 (eq last-command this-command
))
934 (not (equal python-indent-levels
'(0)))
935 (or (python-indent-toggle-levels) t
))
936 (python-indent-calculate-levels))
937 (let* ((starting-pos (point-marker))
938 (indent-ending-position
939 (+ (line-beginning-position) (current-indentation)))
940 (follow-indentation-p
942 (and (<= (line-beginning-position) starting-pos
)
943 (>= indent-ending-position starting-pos
))))
944 (next-indent (nth python-indent-current-level python-indent-levels
)))
945 (unless (= next-indent
(current-indentation))
947 (delete-horizontal-space)
948 (indent-to next-indent
)
949 (goto-char starting-pos
))
950 (and follow-indentation-p
(back-to-indentation)))
951 (python-info-closing-block-message))
953 (defun python-indent-line-function ()
954 "`indent-line-function' for Python mode.
955 See `python-indent-line' for details."
956 (python-indent-line))
958 (defun python-indent-dedent-line ()
959 "De-indent current line."
961 (when (and (not (python-syntax-comment-or-string-p))
962 (<= (point-marker) (save-excursion
963 (back-to-indentation)
965 (> (current-column) 0))
966 (python-indent-line t
)
969 (defun python-indent-dedent-line-backspace (arg)
970 "De-indent current line.
971 Argument ARG is passed to `backward-delete-char-untabify' when
972 point is not in between the indentation."
974 (when (not (python-indent-dedent-line))
975 (backward-delete-char-untabify arg
)))
976 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
978 (defun python-indent-region (start end
)
979 "Indent a python region automagically.
981 Called from a program, START and END specify the region to indent."
982 (let ((deactivate-mark nil
))
985 (setq end
(point-marker))
987 (or (bolp) (forward-line 1))
988 (while (< (point) end
)
989 (or (and (bolp) (eolp))
992 (back-to-indentation)
993 (setq word
(current-word))
996 ;; Don't mess with strings, unless it's the
997 ;; enclosing set of quotes.
998 (or (not (python-syntax-context 'string
))
1002 (current-indentation)
1003 (python-syntax-count-quotes (char-after) (point))))
1004 (string-to-syntax "|"))))
1006 (delete-horizontal-space)
1007 (indent-to (python-indent-calculate-indentation)))))
1009 (move-marker end nil
))))
1011 (defun python-indent-shift-left (start end
&optional count
)
1012 "Shift lines contained in region START END by COUNT columns to the left.
1013 COUNT defaults to `python-indent-offset'. If region isn't
1014 active, the current line is shifted. The shifted region includes
1015 the lines in which START and END lie. An error is signaled if
1016 any lines in the region are indented less than COUNT columns."
1019 (list (region-beginning) (region-end) current-prefix-arg
)
1020 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1022 (setq count
(prefix-numeric-value count
))
1023 (setq count python-indent-offset
))
1025 (let ((deactivate-mark nil
))
1028 (while (< (point) end
)
1029 (if (and (< (current-indentation) count
)
1030 (not (looking-at "[ \t]*$")))
1031 (error "Can't shift all lines enough"))
1033 (indent-rigidly start end
(- count
))))))
1035 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
1037 (defun python-indent-shift-right (start end
&optional count
)
1038 "Shift lines contained in region START END by COUNT columns to the left.
1039 COUNT defaults to `python-indent-offset'. If region isn't
1040 active, the current line is shifted. The shifted region includes
1041 the lines in which START and END lie."
1044 (list (region-beginning) (region-end) current-prefix-arg
)
1045 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1046 (let ((deactivate-mark nil
))
1048 (setq count
(prefix-numeric-value count
))
1049 (setq count python-indent-offset
))
1050 (indent-rigidly start end count
)))
1052 (defun python-indent-electric-colon (arg)
1053 "Insert a colon and maybe de-indent the current line.
1054 With numeric ARG, just insert that many colons. With
1055 \\[universal-argument], just insert a single colon."
1057 (self-insert-command (if (not (integerp arg
)) 1 arg
))
1058 (when (and (not arg
)
1060 (not (equal ?
: (char-after (- (point-marker) 2))))
1061 (not (python-syntax-comment-or-string-p)))
1062 (let ((indentation (current-indentation))
1063 (calculated-indentation (python-indent-calculate-indentation)))
1064 (python-info-closing-block-message)
1065 (when (> indentation calculated-indentation
)
1067 (indent-line-to calculated-indentation
)
1068 (when (not (python-info-closing-block-message))
1069 (indent-line-to indentation
)))))))
1070 (put 'python-indent-electric-colon
'delete-selection t
)
1072 (defun python-indent-post-self-insert-function ()
1073 "Adjust closing paren line indentation after a char is added.
1074 This function is intended to be added to the
1075 `post-self-insert-hook.' If a line renders a paren alone, after
1076 adding a char before it, the line will be re-indented
1077 automatically if needed."
1078 (when (and (eq (char-before) last-command-event
)
1080 (memq (char-after) '(?\
) ?\
] ?\
})))
1082 (goto-char (line-beginning-position))
1083 ;; If after going to the beginning of line the point
1084 ;; is still inside a paren it's ok to do the trick
1085 (when (python-syntax-context 'paren
)
1086 (let ((indentation (python-indent-calculate-indentation)))
1087 (when (< (current-indentation) indentation
)
1088 (indent-line-to indentation
)))))))
1093 (defvar python-nav-beginning-of-defun-regexp
1094 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1095 "Regexp matching class or function definition.
1096 The name of the defun should be grouped so it can be retrieved
1097 via `match-string'.")
1099 (defun python-nav--beginning-of-defun (&optional arg
)
1100 "Internal implementation of `python-nav-beginning-of-defun'.
1101 With positive ARG search backwards, else search forwards."
1102 (when (or (null arg
) (= arg
0)) (setq arg
1))
1103 (let* ((re-search-fn (if (> arg
0)
1104 #'re-search-backward
1105 #'re-search-forward
))
1106 (line-beg-pos (line-beginning-position))
1107 (line-content-start (+ line-beg-pos
(current-indentation)))
1108 (pos (point-marker))
1113 (not (python-info-looking-at-beginning-of-defun))
1114 (python-nav-backward-block)))
1115 (or (and (python-info-looking-at-beginning-of-defun)
1116 (+ (current-indentation) python-indent-offset
))
1120 (when (and (< arg
0)
1121 (python-info-looking-at-beginning-of-defun))
1123 (while (and (funcall re-search-fn
1124 python-nav-beginning-of-defun-regexp nil t
)
1125 (or (python-syntax-context-type)
1126 ;; Handle nested defuns when moving
1127 ;; backwards by checking indentation.
1129 (not (= (current-indentation) 0))
1130 (>= (current-indentation) beg-indentation
)))))
1131 (and (python-info-looking-at-beginning-of-defun)
1132 (or (not (= (line-number-at-pos pos
)
1133 (line-number-at-pos)))
1134 (and (>= (point) line-beg-pos
)
1135 (<= (point) line-content-start
)
1136 (> pos line-content-start
)))))))
1138 (or (beginning-of-line 1) t
)
1139 (and (goto-char pos
) nil
))))
1141 (defun python-nav-beginning-of-defun (&optional arg
)
1142 "Move point to `beginning-of-defun'.
1143 With positive ARG search backwards else search forward. When ARG
1144 is nil or 0 defaults to 1. When searching backwards nested
1145 defuns are handled with care depending on current point
1146 position. Return non-nil if point is moved to
1147 `beginning-of-defun'."
1148 (when (or (null arg
) (= arg
0)) (setq arg
1))
1150 (cond ((and (eq this-command
'mark-defun
)
1151 (python-info-looking-at-beginning-of-defun)))
1153 (dotimes (i (if (> arg
0) arg
(- arg
)))
1154 (when (and (python-nav--beginning-of-defun arg)
1159 (defun python-nav-end-of-defun ()
1160 "Move point to the end of def or class.
1161 Returns nil if point is not in a def or class."
1163 (let ((beg-defun-indent)
1165 (when (or (python-info-looking-at-beginning-of-defun)
1166 (python-nav-beginning-of-defun 1)
1167 (python-nav-beginning-of-defun -1))
1168 (setq beg-defun-indent
(current-indentation))
1170 (python-nav-end-of-statement)
1171 (python-util-forward-comment 1)
1172 (and (> (current-indentation) beg-defun-indent
)
1174 (python-util-forward-comment -
1)
1176 ;; Ensure point moves forward.
1177 (and (> beg-pos
(point)) (goto-char beg-pos
)))))
1179 (defun python-nav-beginning-of-statement ()
1180 "Move to start of current statement."
1182 (while (and (or (back-to-indentation) t
)
1187 (python-info-line-ends-backslash-p))
1188 (python-syntax-context 'string
)
1189 (python-syntax-context 'paren
))
1190 (forward-line -
1))))
1193 (defun python-nav-end-of-statement (&optional noend
)
1194 "Move to end of current statement.
1195 Optional argument NOEND is internal and makes the logic to not
1196 jump to the end of line when moving forward searching for the end
1199 (let (string-start bs-pos
)
1200 (while (and (or noend
(goto-char (line-end-position)))
1202 (cond ((setq string-start
(python-syntax-context 'string
))
1203 (goto-char string-start
)
1204 (if (python-syntax-context 'paren
)
1205 ;; Ended up inside a paren, roll again.
1206 (python-nav-end-of-statement t
)
1207 ;; This is not inside a paren, move to the
1208 ;; end of this string.
1209 (goto-char (+ (point)
1210 (python-syntax-count-quotes
1211 (char-after (point)) (point))))
1212 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
1213 (goto-char (point-max)))))
1214 ((python-syntax-context 'paren
)
1215 ;; The statement won't end before we've escaped
1216 ;; at least one level of parenthesis.
1218 (goto-char (scan-lists (point) 1 -
1))
1219 (scan-error (goto-char (nth 3 err
)))))
1220 ((setq bs-pos
(python-info-line-ends-backslash-p))
1222 (forward-line 1))))))
1225 (defun python-nav-backward-statement (&optional arg
)
1226 "Move backward to previous statement.
1227 With ARG, repeat. See `python-nav-forward-statement'."
1229 (or arg
(setq arg
1))
1230 (python-nav-forward-statement (- arg
)))
1232 (defun python-nav-forward-statement (&optional arg
)
1233 "Move forward to next statement.
1234 With ARG, repeat. With negative argument, move ARG times
1235 backward to previous statement."
1237 (or arg
(setq arg
1))
1239 (python-nav-end-of-statement)
1240 (python-util-forward-comment)
1241 (python-nav-beginning-of-statement)
1242 (setq arg
(1- arg
)))
1244 (python-nav-beginning-of-statement)
1245 (python-util-forward-comment -
1)
1246 (python-nav-beginning-of-statement)
1247 (setq arg
(1+ arg
))))
1249 (defun python-nav-beginning-of-block ()
1250 "Move to start of current block."
1252 (let ((starting-pos (point))
1253 (block-regexp (python-rx
1254 line-start
(* whitespace
) block-start
)))
1256 (python-nav-beginning-of-statement)
1257 (looking-at (python-rx block-start
)))
1259 ;; Go to first line beginning a statement
1260 (while (and (not (bobp))
1261 (or (and (python-nav-beginning-of-statement) nil
)
1262 (python-info-current-line-comment-p)
1263 (python-info-current-line-empty-p)))
1265 (let ((block-matching-indent
1266 (- (current-indentation) python-indent-offset
)))
1268 (and (python-nav-backward-block)
1269 (> (current-indentation) block-matching-indent
)))
1270 (if (and (looking-at (python-rx block-start
))
1271 (= (current-indentation) block-matching-indent
))
1273 (and (goto-char starting-pos
) nil
))))))
1275 (defun python-nav-end-of-block ()
1276 "Move to end of current block."
1278 (when (python-nav-beginning-of-block)
1279 (let ((block-indentation (current-indentation)))
1280 (python-nav-end-of-statement)
1281 (while (and (forward-line 1)
1283 (or (and (> (current-indentation) block-indentation
)
1284 (or (python-nav-end-of-statement) t
))
1285 (python-info-current-line-comment-p)
1286 (python-info-current-line-empty-p))))
1287 (python-util-forward-comment -
1)
1290 (defun python-nav-backward-block (&optional arg
)
1291 "Move backward to previous block of code.
1292 With ARG, repeat. See `python-nav-forward-block'."
1294 (or arg
(setq arg
1))
1295 (python-nav-forward-block (- arg
)))
1297 (defun python-nav-forward-block (&optional arg
)
1298 "Move forward to next block of code.
1299 With ARG, repeat. With negative argument, move ARG times
1300 backward to previous block."
1302 (or arg
(setq arg
1))
1303 (let ((block-start-regexp
1304 (python-rx line-start
(* whitespace
) block-start
))
1305 (starting-pos (point)))
1307 (python-nav-end-of-statement)
1309 (re-search-forward block-start-regexp nil t
)
1310 (python-syntax-context-type)))
1311 (setq arg
(1- arg
)))
1313 (python-nav-beginning-of-statement)
1315 (re-search-backward block-start-regexp nil t
)
1316 (python-syntax-context-type)))
1317 (setq arg
(1+ arg
)))
1318 (python-nav-beginning-of-statement)
1319 (if (not (looking-at (python-rx block-start
)))
1320 (and (goto-char starting-pos
) nil
)
1321 (and (not (= (point) starting-pos
)) (point-marker)))))
1323 (defun python-nav-lisp-forward-sexp-safe (&optional arg
)
1324 "Safe version of standard `forward-sexp'.
1325 When ARG > 0 move forward, else if ARG is < 0."
1326 (or arg
(setq arg
1))
1327 (let ((forward-sexp-function)
1329 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1331 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1335 (while (and (funcall search-fn paren-regexp nil t
)
1336 (python-syntax-context 'paren
)))))))
1338 (defun python-nav--forward-sexp (&optional dir
)
1339 "Move to forward sexp.
1340 With positive Optional argument DIR direction move forward, else
1342 (setq dir
(or dir
1))
1344 (let* ((forward-p (if (> dir
0)
1345 (and (setq dir
1) t
)
1346 (and (setq dir -
1) nil
)))
1347 (re-search-fn (if forward-p
1349 're-search-backward
))
1350 (context-type (python-syntax-context-type)))
1352 ((eq context-type
'string
)
1353 ;; Inside of a string, get out of it.
1354 (while (and (funcall re-search-fn
"[\"']" nil t
)
1355 (python-syntax-context 'string
))))
1356 ((eq context-type
'comment
)
1357 ;; Inside of a comment, just move forward.
1358 (python-util-forward-comment dir
))
1359 ((or (eq context-type
'paren
)
1360 (and forward-p
(looking-at (python-rx open-paren
)))
1361 (and (not forward-p
)
1362 (eq (syntax-class (syntax-after (1- (point))))
1363 (car (string-to-syntax ")")))))
1364 ;; Inside a paren or looking at it, lisp knows what to do.
1365 (python-nav-lisp-forward-sexp-safe dir
))
1367 ;; This part handles the lispy feel of
1368 ;; `python-nav-forward-sexp'. Knowing everything about the
1369 ;; current context and the context of the next sexp tries to
1370 ;; follow the lisp sexp motion commands in a symmetric manner.
1373 ((python-info-beginning-of-block-p) 'block-start
)
1374 ((python-info-end-of-block-p) 'block-end
)
1375 ((python-info-beginning-of-statement-p) 'statement-start
)
1376 ((python-info-end-of-statement-p) 'statement-end
)))
1379 (python-nav-lisp-forward-sexp-safe dir
)
1383 (goto-char next-sexp-pos
)
1385 ((python-info-beginning-of-block-p) 'block-start
)
1386 ((python-info-end-of-block-p) 'block-end
)
1387 ((python-info-beginning-of-statement-p) 'statement-start
)
1388 ((python-info-end-of-statement-p) 'statement-end
)
1389 ((python-info-statement-starts-block-p) 'starts-block
)
1390 ((python-info-statement-ends-block-p) 'ends-block
)))))
1392 (cond ((and (not (eobp))
1393 (python-info-current-line-empty-p))
1394 (python-util-forward-comment dir
)
1395 (python-nav--forward-sexp dir
))
1396 ((eq context
'block-start
)
1397 (python-nav-end-of-block))
1398 ((eq context
'statement-start
)
1399 (python-nav-end-of-statement))
1400 ((and (memq context
'(statement-end block-end
))
1401 (eq next-sexp-context
'ends-block
))
1402 (goto-char next-sexp-pos
)
1403 (python-nav-end-of-block))
1404 ((and (memq context
'(statement-end block-end
))
1405 (eq next-sexp-context
'starts-block
))
1406 (goto-char next-sexp-pos
)
1407 (python-nav-end-of-block))
1408 ((memq context
'(statement-end block-end
))
1409 (goto-char next-sexp-pos
)
1410 (python-nav-end-of-statement))
1411 (t (goto-char next-sexp-pos
)))
1412 (cond ((and (not (bobp))
1413 (python-info-current-line-empty-p))
1414 (python-util-forward-comment dir
)
1415 (python-nav--forward-sexp dir
))
1416 ((eq context
'block-end
)
1417 (python-nav-beginning-of-block))
1418 ((eq context
'statement-end
)
1419 (python-nav-beginning-of-statement))
1420 ((and (memq context
'(statement-start block-start
))
1421 (eq next-sexp-context
'starts-block
))
1422 (goto-char next-sexp-pos
)
1423 (python-nav-beginning-of-block))
1424 ((and (memq context
'(statement-start block-start
))
1425 (eq next-sexp-context
'ends-block
))
1426 (goto-char next-sexp-pos
)
1427 (python-nav-beginning-of-block))
1428 ((memq context
'(statement-start block-start
))
1429 (goto-char next-sexp-pos
)
1430 (python-nav-beginning-of-statement))
1431 (t (goto-char next-sexp-pos
))))))))))
1433 (defun python-nav--backward-sexp ()
1434 "Move to backward sexp."
1435 (python-nav--forward-sexp -
1))
1437 (defun python-nav-forward-sexp (&optional arg
)
1438 "Move forward across one block of code.
1439 With ARG, do it that many times. Negative arg -N means
1440 move backward N times."
1442 (or arg
(setq arg
1))
1444 (python-nav--forward-sexp)
1445 (setq arg
(1- arg
)))
1447 (python-nav--backward-sexp)
1448 (setq arg
(1+ arg
))))
1450 (defun python-nav--up-list (&optional dir
)
1451 "Internal implementation of `python-nav-up-list'.
1452 DIR is always 1 or -1 and comes sanitized from
1453 `python-nav-up-list' calls."
1454 (let ((context (python-syntax-context-type))
1455 (forward-p (> dir
0)))
1457 ((memq context
'(string comment
)))
1458 ((eq context
'paren
)
1459 (let ((forward-sexp-function))
1461 ((and forward-p
(python-info-end-of-block-p))
1462 (let ((parent-end-pos
1464 (let ((indentation (and
1465 (python-nav-beginning-of-block)
1466 (current-indentation))))
1467 (while (and indentation
1469 (>= (current-indentation) indentation
)
1470 (python-nav-backward-block)))
1471 (python-nav-end-of-block)))))
1472 (and (> (or parent-end-pos
(point)) (point))
1473 (goto-char parent-end-pos
))))
1474 (forward-p (python-nav-end-of-block))
1475 ((and (not forward-p
)
1476 (> (current-indentation) 0)
1477 (python-info-beginning-of-block-p))
1478 (let ((prev-block-pos
1480 (let ((indentation (current-indentation)))
1481 (while (and (python-nav-backward-block)
1482 (>= (current-indentation) indentation
))))
1484 (and (> (point) prev-block-pos
)
1485 (goto-char prev-block-pos
))))
1486 ((not forward-p
) (python-nav-beginning-of-block)))))
1488 (defun python-nav-up-list (&optional arg
)
1489 "Move forward out of one level of parentheses (or blocks).
1490 With ARG, do this that many times.
1491 A negative argument means move backward but still to a less deep spot.
1492 This command assumes point is not in a string or comment."
1494 (or arg
(setq arg
1))
1496 (python-nav--up-list 1)
1497 (setq arg
(1- arg
)))
1499 (python-nav--up-list -
1)
1500 (setq arg
(1+ arg
))))
1502 (defun python-nav-backward-up-list (&optional arg
)
1503 "Move backward out of one level of parentheses (or blocks).
1504 With ARG, do this that many times.
1505 A negative argument means move backward but still to a less deep spot.
1506 This command assumes point is not in a string or comment."
1508 (or arg
(setq arg
1))
1509 (python-nav-up-list (- arg
)))
1512 ;;; Shell integration
1514 (defcustom python-shell-buffer-name
"Python"
1515 "Default buffer name for Python interpreter."
1520 (defcustom python-shell-interpreter
"python"
1521 "Default Python interpreter for shell."
1525 (defcustom python-shell-internal-buffer-name
"Python Internal"
1526 "Default buffer name for the Internal Python interpreter."
1531 (defcustom python-shell-interpreter-args
"-i"
1532 "Default arguments for the Python interpreter."
1536 (defcustom python-shell-prompt-regexp
">>> "
1537 "Regular Expression matching top\-level input prompt of python shell.
1538 It should not contain a caret (^) at the beginning."
1543 (defcustom python-shell-prompt-block-regexp
"[.][.][.] "
1544 "Regular Expression matching block input prompt of python shell.
1545 It should not contain a caret (^) at the beginning."
1550 (defcustom python-shell-prompt-output-regexp
""
1551 "Regular Expression matching output prompt of python shell.
1552 It should not contain a caret (^) at the beginning."
1557 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1558 "Regular Expression matching pdb input prompt of python shell.
1559 It should not contain a caret (^) at the beginning."
1564 (defcustom python-shell-enable-font-lock t
1565 "Should syntax highlighting be enabled in the python shell buffer?
1566 Restart the python shell after changing this variable for it to take effect."
1571 (defcustom python-shell-process-environment nil
1572 "List of environment variables for Python shell.
1573 This variable follows the same rules as `process-environment'
1574 since it merges with it before the process creation routines are
1575 called. When this variable is nil, the Python shell is run with
1576 the default `process-environment'."
1577 :type
'(repeat string
)
1581 (defcustom python-shell-extra-pythonpaths nil
1582 "List of extra pythonpaths for Python shell.
1583 The values of this variable are added to the existing value of
1584 PYTHONPATH in the `process-environment' variable."
1585 :type
'(repeat string
)
1589 (defcustom python-shell-exec-path nil
1590 "List of path to search for binaries.
1591 This variable follows the same rules as `exec-path' since it
1592 merges with it before the process creation routines are called.
1593 When this variable is nil, the Python shell is run with the
1594 default `exec-path'."
1595 :type
'(repeat string
)
1599 (defcustom python-shell-virtualenv-path nil
1600 "Path to virtualenv root.
1601 This variable, when set to a string, makes the values stored in
1602 `python-shell-process-environment' and `python-shell-exec-path'
1603 to be modified properly so shells are started with the specified
1609 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1610 python-ffap-setup-code
1611 python-eldoc-setup-code
)
1612 "List of code run by `python-shell-send-setup-codes'."
1613 :type
'(repeat symbol
)
1617 (defcustom python-shell-compilation-regexp-alist
1618 `((,(rx line-start
(1+ (any " \t")) "File \""
1619 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1620 "\", line " (group (1+ digit
)))
1622 (,(rx " in file " (group (1+ not-newline
)) " on line "
1625 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1626 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1628 "`compilation-error-regexp-alist' for inferior Python."
1629 :type
'(alist string
)
1632 (defun python-shell-get-process-name (dedicated)
1633 "Calculate the appropriate process name for inferior Python process.
1634 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1635 returns a string with the form
1636 `python-shell-buffer-name'[variable `buffer-file-name'] else
1637 returns the value of `python-shell-buffer-name'."
1641 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
1642 (format "%s" python-shell-buffer-name
))))
1645 (defun python-shell-internal-get-process-name ()
1646 "Calculate the appropriate process name for Internal Python process.
1647 The name is calculated from `python-shell-global-buffer-name' and
1648 a hash of all relevant global shell settings in order to ensure
1649 uniqueness for different types of configurations."
1651 python-shell-internal-buffer-name
1654 (python-shell-parse-command)
1655 python-shell-prompt-regexp
1656 python-shell-prompt-block-regexp
1657 python-shell-prompt-output-regexp
1658 (mapconcat #'symbol-value python-shell-setup-codes
"")
1659 (mapconcat #'identity python-shell-process-environment
"")
1660 (mapconcat #'identity python-shell-extra-pythonpaths
"")
1661 (mapconcat #'identity python-shell-exec-path
"")
1662 (or python-shell-virtualenv-path
"")
1663 (mapconcat #'identity python-shell-exec-path
"")))))
1665 (defun python-shell-parse-command ()
1666 "Calculate the string used to execute the inferior Python process."
1667 (format "%s %s" python-shell-interpreter python-shell-interpreter-args
))
1669 (defun python-shell-calculate-process-environment ()
1670 "Calculate process environment given `python-shell-virtualenv-path'."
1671 (let ((process-environment (append
1672 python-shell-process-environment
1673 process-environment nil
))
1674 (virtualenv (if python-shell-virtualenv-path
1675 (directory-file-name python-shell-virtualenv-path
)
1677 (when python-shell-extra-pythonpaths
1678 (setenv "PYTHONPATH"
1680 (mapconcat 'identity
1681 python-shell-extra-pythonpaths
1684 (or (getenv "PYTHONPATH") ""))))
1685 (if (not virtualenv
)
1687 (setenv "PYTHONHOME" nil
)
1688 (setenv "PATH" (format "%s/bin%s%s"
1689 virtualenv path-separator
1690 (or (getenv "PATH") "")))
1691 (setenv "VIRTUAL_ENV" virtualenv
))
1692 process-environment
))
1694 (defun python-shell-calculate-exec-path ()
1695 "Calculate exec path given `python-shell-virtualenv-path'."
1696 (let ((path (append python-shell-exec-path
1698 (if (not python-shell-virtualenv-path
)
1700 (cons (format "%s/bin"
1701 (directory-file-name python-shell-virtualenv-path
))
1704 (defun python-comint-output-filter-function (output)
1705 "Hook run after content is put into comint buffer.
1706 OUTPUT is a string with the contents of the buffer."
1707 (ansi-color-filter-apply output
))
1709 (defvar python-shell--parent-buffer nil
)
1711 (defvar python-shell-output-syntax-table
1712 (let ((table (make-syntax-table python-dotty-syntax-table
)))
1713 (modify-syntax-entry ?
\' "." table
)
1714 (modify-syntax-entry ?
\" "." table
)
1715 (modify-syntax-entry ?\
( "." table
)
1716 (modify-syntax-entry ?\
[ "." table
)
1717 (modify-syntax-entry ?\
{ "." table
)
1718 (modify-syntax-entry ?\
) "." table
)
1719 (modify-syntax-entry ?\
] "." table
)
1720 (modify-syntax-entry ?\
} "." table
)
1722 "Syntax table for shell output.
1723 It makes parens and quotes be treated as punctuation chars.")
1725 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1726 "Major mode for Python inferior process.
1727 Runs a Python interpreter as a subprocess of Emacs, with Python
1728 I/O through an Emacs buffer. Variables
1729 `python-shell-interpreter' and `python-shell-interpreter-args'
1730 controls which Python interpreter is run. Variables
1731 `python-shell-prompt-regexp',
1732 `python-shell-prompt-output-regexp',
1733 `python-shell-prompt-block-regexp',
1734 `python-shell-enable-font-lock',
1735 `python-shell-completion-setup-code',
1736 `python-shell-completion-string-code',
1737 `python-shell-completion-module-string-code',
1738 `python-eldoc-setup-code', `python-eldoc-string-code',
1739 `python-ffap-setup-code' and `python-ffap-string-code' can
1740 customize this mode for different Python interpreters.
1742 You can also add additional setup code to be run at
1743 initialization of the interpreter via `python-shell-setup-codes'
1746 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1747 (and python-shell--parent-buffer
1748 (python-util-clone-local-variables python-shell--parent-buffer
))
1749 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1750 python-shell-prompt-regexp
1751 python-shell-prompt-block-regexp
1752 python-shell-prompt-pdb-regexp
))
1753 (setq mode-line-process
'(":%s"))
1754 (make-local-variable 'comint-output-filter-functions
)
1755 (add-hook 'comint-output-filter-functions
1756 'python-comint-output-filter-function
)
1757 (add-hook 'comint-output-filter-functions
1758 'python-pdbtrack-comint-output-filter-function
)
1759 (set (make-local-variable 'compilation-error-regexp-alist
)
1760 python-shell-compilation-regexp-alist
)
1761 (define-key inferior-python-mode-map
[remap complete-symbol
]
1762 'completion-at-point
)
1763 (add-hook 'completion-at-point-functions
1764 'python-shell-completion-complete-at-point nil
'local
)
1765 (add-to-list (make-local-variable 'comint-dynamic-complete-functions
)
1766 'python-shell-completion-complete-at-point
)
1767 (define-key inferior-python-mode-map
"\t"
1768 'python-shell-completion-complete-or-indent
)
1769 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
1770 (make-local-variable 'python-pdbtrack-tracked-buffer
)
1771 (make-local-variable 'python-shell-internal-last-output
)
1772 (when python-shell-enable-font-lock
1773 (set-syntax-table python-mode-syntax-table
)
1774 (set (make-local-variable 'font-lock-defaults
)
1775 '(python-font-lock-keywords nil nil nil nil
))
1776 (set (make-local-variable 'syntax-propertize-function
)
1778 ;; XXX: Unfortunately eval is needed here to make use of the
1779 ;; dynamic value of `comint-prompt-regexp'.
1780 `(syntax-propertize-rules
1781 (,comint-prompt-regexp
1784 comint-last-input-start end
'syntax-table
1785 python-shell-output-syntax-table
)
1786 ;; XXX: This might look weird, but it is the easiest
1787 ;; way to ensure font lock gets cleaned up before the
1788 ;; current prompt, which is needed for unclosed
1789 ;; strings to not mess up with current input.
1790 (font-lock-unfontify-region comint-last-input-start end
))))
1791 (,(python-rx string-delimiter
)
1793 (and (not (eq (get-text-property start
'field
) 'output
))
1794 (python-syntax-stringify)))))))))
1795 (compilation-shell-minor-mode 1))
1797 (defun python-shell-make-comint (cmd proc-name
&optional pop internal
)
1798 "Create a python shell comint buffer.
1799 CMD is the python command to be executed and PROC-NAME is the
1800 process name the comint buffer will get. After the comint buffer
1801 is created the `inferior-python-mode' is activated. When
1802 optional argument POP is non-nil the buffer is shown. When
1803 optional argument INTERNAL is non-nil this process is run on a
1804 buffer with a name that starts with a space, following the Emacs
1805 convention for temporary/internal buffers, and also makes sure
1806 the user is not queried for confirmation when the process is
1809 (let* ((proc-buffer-name
1810 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
1811 (process-environment (python-shell-calculate-process-environment))
1812 (exec-path (python-shell-calculate-exec-path)))
1813 (when (not (comint-check-proc proc-buffer-name
))
1814 (let* ((cmdlist (split-string-and-unquote cmd
))
1815 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1816 (car cmdlist
) nil
(cdr cmdlist
)))
1817 (python-shell--parent-buffer (current-buffer))
1818 (process (get-buffer-process buffer
)))
1819 (with-current-buffer buffer
1820 (inferior-python-mode))
1821 (accept-process-output process
)
1822 (and pop
(pop-to-buffer buffer t
))
1823 (and internal
(set-process-query-on-exit-flag process nil
))))
1827 (defun run-python (cmd &optional dedicated show
)
1828 "Run an inferior Python process.
1829 Input and output via buffer named after
1830 `python-shell-buffer-name'. If there is a process already
1831 running in that buffer, just switch to it.
1833 With argument, allows you to define CMD so you can edit the
1834 command used to call the interpreter and define DEDICATED, so a
1835 dedicated process for the current buffer is open. When numeric
1836 prefix arg is other than 0 or 4 do not SHOW.
1838 Runs the hook `inferior-python-mode-hook' (after the
1839 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1840 process buffer for a list of commands.)"
1842 (if current-prefix-arg
1844 (read-string "Run Python: " (python-shell-parse-command))
1845 (y-or-n-p "Make dedicated process? ")
1846 (= (prefix-numeric-value current-prefix-arg
) 4))
1847 (list (python-shell-parse-command) nil t
)))
1848 (python-shell-make-comint
1849 cmd
(python-shell-get-process-name dedicated
) show
)
1852 (defun run-python-internal ()
1853 "Run an inferior Internal Python process.
1854 Input and output via buffer named after
1855 `python-shell-internal-buffer-name' and what
1856 `python-shell-internal-get-process-name' returns.
1858 This new kind of shell is intended to be used for generic
1859 communication related to defined configurations, the main
1860 difference with global or dedicated shells is that these ones are
1861 attached to a configuration, not a buffer. This means that can
1862 be used for example to retrieve the sys.path and other stuff,
1863 without messing with user shells. Note that
1864 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
1865 are set to nil for these shells, so setup codes are not sent at
1867 (let ((python-shell-enable-font-lock nil
)
1868 (inferior-python-mode-hook nil
))
1870 (python-shell-make-comint
1871 (python-shell-parse-command)
1872 (python-shell-internal-get-process-name) nil t
))))
1874 (defun python-shell-get-process ()
1875 "Get inferior Python process for current buffer and return it."
1876 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1877 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1878 (global-proc-name (python-shell-get-process-name nil
))
1879 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1880 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1881 (global-running (comint-check-proc global-proc-buffer-name
)))
1882 ;; Always prefer dedicated
1883 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name
)
1884 (and global-running global-proc-buffer-name
)))))
1886 (defun python-shell-get-or-create-process ()
1887 "Get or create an inferior Python process for current buffer and return it."
1888 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1889 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1890 (global-proc-name (python-shell-get-process-name nil
))
1891 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1892 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1893 (global-running (comint-check-proc global-proc-buffer-name
))
1894 (current-prefix-arg 16))
1895 (when (and (not dedicated-running
) (not global-running
))
1896 (if (call-interactively 'run-python
)
1897 (setq dedicated-running t
)
1898 (setq global-running t
)))
1899 ;; Always prefer dedicated
1900 (get-buffer-process (if dedicated-running
1901 dedicated-proc-buffer-name
1902 global-proc-buffer-name
))))
1904 (defvar python-shell-internal-buffer nil
1905 "Current internal shell buffer for the current buffer.
1906 This is really not necessary at all for the code to work but it's
1907 there for compatibility with CEDET.")
1909 (defvar python-shell-internal-last-output nil
1910 "Last output captured by the internal shell.
1911 This is really not necessary at all for the code to work but it's
1912 there for compatibility with CEDET.")
1914 (defun python-shell-internal-get-or-create-process ()
1915 "Get or create an inferior Internal Python process."
1916 (let* ((proc-name (python-shell-internal-get-process-name))
1917 (proc-buffer-name (format " *%s*" proc-name
)))
1918 (when (not (process-live-p proc-name
))
1919 (run-python-internal)
1920 (setq python-shell-internal-buffer proc-buffer-name
)
1921 ;; XXX: Why is this `sit-for' needed?
1922 ;; `python-shell-make-comint' calls `accept-process-output'
1923 ;; already but it is not helping to get proper output on
1924 ;; 'gnu/linux when the internal shell process is not running and
1925 ;; a call to `python-shell-internal-send-string' is issued.
1927 (get-buffer-process proc-buffer-name
)))
1929 (define-obsolete-function-alias
1930 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
1932 (define-obsolete-variable-alias
1933 'python-buffer
'python-shell-internal-buffer
"24.3")
1935 (define-obsolete-variable-alias
1936 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
1938 (defun python-shell-send-string (string &optional process msg
)
1939 "Send STRING to inferior Python PROCESS.
1940 When MSG is non-nil messages the first line of STRING."
1941 (interactive "sPython command: ")
1942 (let ((process (or process
(python-shell-get-or-create-process)))
1943 (lines (split-string string
"\n" t
)))
1944 (and msg
(message "Sent: %s..." (nth 0 lines
)))
1945 (if (> (length lines
) 1)
1946 (let* ((temporary-file-directory
1947 (if (file-remote-p default-directory
)
1948 (concat (file-remote-p default-directory
) "/tmp")
1949 temporary-file-directory
))
1950 (temp-file-name (make-temp-file "py"))
1951 (file-name (or (buffer-file-name) temp-file-name
)))
1952 (with-temp-file temp-file-name
1954 (delete-trailing-whitespace))
1955 (python-shell-send-file file-name process temp-file-name
))
1956 (comint-send-string process string
)
1957 (when (or (not (string-match "\n$" string
))
1958 (string-match "\n[ \t].*\n?$" string
))
1959 (comint-send-string process
"\n")))))
1961 (defvar python-shell-output-filter-in-progress nil
)
1962 (defvar python-shell-output-filter-buffer nil
)
1964 (defun python-shell-output-filter (string)
1965 "Filter used in `python-shell-send-string-no-output' to grab output.
1966 STRING is the output received to this point from the process.
1967 This filter saves received output from the process in
1968 `python-shell-output-filter-buffer' and stops receiving it after
1969 detecting a prompt at the end of the buffer."
1971 string
(ansi-color-filter-apply string
)
1972 python-shell-output-filter-buffer
1973 (concat python-shell-output-filter-buffer string
))
1975 ;; XXX: It seems on OSX an extra carriage return is attached
1976 ;; at the end of output, this handles that too.
1977 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$"
1978 python-shell-prompt-regexp
1979 python-shell-prompt-block-regexp
1980 python-shell-prompt-pdb-regexp
)
1981 python-shell-output-filter-buffer
)
1982 ;; Output ends when `python-shell-output-filter-buffer' contains
1983 ;; the prompt attached at the end of it.
1984 (setq python-shell-output-filter-in-progress nil
1985 python-shell-output-filter-buffer
1986 (substring python-shell-output-filter-buffer
1987 0 (match-beginning 0)))
1988 (when (and (> (length python-shell-prompt-output-regexp
) 0)
1989 (string-match (concat "^" python-shell-prompt-output-regexp
)
1990 python-shell-output-filter-buffer
))
1991 ;; Some shells, like iPython might append a prompt before the
1992 ;; output, clean that.
1993 (setq python-shell-output-filter-buffer
1994 (substring python-shell-output-filter-buffer
(match-end 0)))))
1997 (defun python-shell-send-string-no-output (string &optional process msg
)
1998 "Send STRING to PROCESS and inhibit output.
1999 When MSG is non-nil messages the first line of STRING. Return
2001 (let ((process (or process
(python-shell-get-or-create-process)))
2002 (comint-preoutput-filter-functions
2003 '(python-shell-output-filter))
2004 (python-shell-output-filter-in-progress t
)
2008 (python-shell-send-string string process msg
)
2009 (while python-shell-output-filter-in-progress
2010 ;; `python-shell-output-filter' takes care of setting
2011 ;; `python-shell-output-filter-in-progress' to NIL after it
2012 ;; detects end of output.
2013 (accept-process-output process
))
2015 python-shell-output-filter-buffer
2016 (setq python-shell-output-filter-buffer nil
)))
2017 (with-current-buffer (process-buffer process
)
2018 (comint-interrupt-subjob)))))
2020 (defun python-shell-internal-send-string (string)
2021 "Send STRING to the Internal Python interpreter.
2022 Returns the output. See `python-shell-send-string-no-output'."
2023 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2024 ;; updated to support this new mode.
2025 (setq python-shell-internal-last-output
2026 (python-shell-send-string-no-output
2027 ;; Makes this function compatible with the old
2028 ;; python-send-receive. (At least for CEDET).
2029 (replace-regexp-in-string "_emacs_out +" "" string
)
2030 (python-shell-internal-get-or-create-process) nil
)))
2032 (define-obsolete-function-alias
2033 'python-send-receive
'python-shell-internal-send-string
"24.3")
2035 (define-obsolete-function-alias
2036 'python-send-string
'python-shell-internal-send-string
"24.3")
2038 (defun python-shell-send-region (start end
)
2039 "Send the region delimited by START and END to inferior Python process."
2041 (python-shell-send-string
2043 (let ((line-num (line-number-at-pos start
)))
2044 ;; When sending a region, add blank lines for non sent code so
2045 ;; backtraces remain correct.
2046 (make-string (1- line-num
) ?
\n))
2047 (buffer-substring start end
))
2050 (defun python-shell-send-buffer (&optional arg
)
2051 "Send the entire buffer to inferior Python process.
2052 With prefix ARG allow execution of code inside blocks delimited
2053 by \"if __name__== '__main__':\""
2057 (let ((str (buffer-substring (point-min) (point-max))))
2060 (setq str
(replace-regexp-in-string
2061 (python-rx if-name-main
)
2062 "if __name__ == '__main__ ':" str
)))
2063 (python-shell-send-string str
))))
2065 (defun python-shell-send-defun (arg)
2066 "Send the current defun to inferior Python process.
2067 When argument ARG is non-nil do not include decorators."
2070 (python-shell-send-region
2073 (while (and (or (python-nav-beginning-of-defun)
2074 (beginning-of-line 1))
2075 (> (current-indentation) 0)))
2077 (while (and (forward-line -
1)
2078 (looking-at (python-rx decorator
))))
2082 (or (python-nav-end-of-defun)
2086 (defun python-shell-send-file (file-name &optional process temp-file-name
)
2087 "Send FILE-NAME to inferior Python PROCESS.
2088 If TEMP-FILE-NAME is passed then that file is used for processing
2089 instead, while internally the shell will continue to use
2091 (interactive "fFile to send: ")
2092 (let* ((process (or process
(python-shell-get-or-create-process)))
2093 (temp-file-name (when temp-file-name
2095 (or (file-remote-p temp-file-name
'localname
)
2097 (file-name (or (when file-name
2099 (or (file-remote-p file-name
'localname
)
2102 (when (not file-name
)
2103 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2104 (python-shell-send-string
2106 (concat "__pyfile = open('''%s''');"
2107 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2109 (or temp-file-name file-name
) file-name
)
2112 (defun python-shell-switch-to-shell ()
2113 "Switch to inferior Python process buffer."
2115 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
2117 (defun python-shell-send-setup-code ()
2118 "Send all setup code for shell.
2119 This function takes the list of setup code to send from the
2120 `python-shell-setup-codes' list."
2121 (let ((process (get-buffer-process (current-buffer))))
2122 (dolist (code python-shell-setup-codes
)
2124 (message "Sent %s" code
)
2125 (python-shell-send-string
2126 (symbol-value code
) process
)))))
2128 (add-hook 'inferior-python-mode-hook
2129 #'python-shell-send-setup-code
)
2132 ;;; Shell completion
2134 (defcustom python-shell-completion-setup-code
2138 def __COMPLETER_all_completions(text): []
2141 readline.set_completer(rlcompleter.Completer().complete)
2142 def __COMPLETER_all_completions(text):
2148 res = readline.get_completer()(text, i)
2151 completions.append(res)
2155 "Code used to setup completion in inferior Python processes."
2159 (defcustom python-shell-completion-string-code
2160 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2161 "Python code used to get a string of completions separated by semicolons."
2165 (defcustom python-shell-completion-module-string-code
""
2166 "Python code used to get completions separated by semicolons for imports.
2168 For IPython v0.11, add the following line to
2169 `python-shell-completion-setup-code':
2171 from IPython.core.completerlib import module_completion
2173 and use the following as the value of this variable:
2175 ';'.join(module_completion('''%s'''))\n"
2179 (defcustom python-shell-completion-pdb-string-code
2180 "';'.join(globals().keys() + locals().keys())"
2181 "Python code used to get completions separated by semicolons for [i]pdb."
2185 (defun python-shell-completion-get-completions (process line input
)
2186 "Do completion at point for PROCESS.
2187 LINE is used to detect the context on how to complete given
2190 ;; Get the last prompt for the inferior process
2191 ;; buffer. This is used for the completion code selection
2193 (with-current-buffer (process-buffer process
)
2194 (buffer-substring-no-properties
2195 (overlay-start comint-last-prompt-overlay
)
2196 (overlay-end comint-last-prompt-overlay
))))
2198 ;; Check whether a prompt matches a pdb string, an import
2199 ;; statement or just the standard prompt and use the
2200 ;; correct python-shell-completion-*-code string
2201 (cond ((and (> (length python-shell-completion-pdb-string-code
) 0)
2203 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
2206 (length python-shell-completion-module-string-code
) 0)
2208 (concat "^" python-shell-prompt-regexp
) prompt
)
2209 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line
))
2212 (concat "^" python-shell-prompt-regexp
) prompt
)
2216 (pcase completion-context
2217 (`pdb python-shell-completion-pdb-string-code
)
2218 (`import python-shell-completion-module-string-code
)
2219 (`default python-shell-completion-string-code
)
2222 (if (eq completion-context
'import
)
2223 (replace-regexp-in-string "^[ \t]+" "" line
)
2225 (and completion-code
2226 (> (length input
) 0)
2227 (with-current-buffer (process-buffer process
)
2228 (let ((completions (python-shell-send-string-no-output
2229 (format completion-code input
) process
)))
2230 (and (> (length completions
) 2)
2231 (split-string completions
2232 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
2234 (defun python-shell-completion-complete-at-point (&optional process
)
2235 "Perform completion at point in inferior Python.
2236 Optional argument PROCESS forces completions to be retrieved
2237 using that one instead of current buffer's process."
2238 (setq process
(or process
(get-buffer-process (current-buffer))))
2241 (with-syntax-table python-dotty-syntax-table
2242 (let* ((paren-depth (car (syntax-ppss)))
2243 (syntax-string "w_")
2244 (syntax-list (string-to-syntax syntax-string
)))
2245 ;; Stop scanning for the beginning of the completion
2246 ;; subject after the char before point matches a
2249 (car (syntax-after (1- (point)))) syntax-list
)
2250 (skip-syntax-backward syntax-string
)
2251 (when (or (equal (char-before) ?\
))
2252 (equal (char-before) ?
\"))
2255 ;; honor initial paren depth
2256 (> (car (syntax-ppss)) paren-depth
)
2257 (python-syntax-context 'string
))
2262 (completion-table-dynamic
2264 #'python-shell-completion-get-completions
2265 process
(buffer-substring-no-properties
2266 (line-beginning-position) end
))))))
2268 (defun python-shell-completion-complete-or-indent ()
2269 "Complete or indent depending on the context.
2270 If content before pointer is all whitespace indent. If not try
2273 (if (string-match "^[[:space:]]*$"
2274 (buffer-substring (comint-line-beginning-position)
2276 (indent-for-tab-command)
2277 (completion-at-point)))
2280 ;;; PDB Track integration
2282 (defcustom python-pdbtrack-activate t
2283 "Non-nil makes python shell enable pdbtracking."
2288 (defcustom python-pdbtrack-stacktrace-info-regexp
2289 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2290 "Regular Expression matching stacktrace information.
2291 Used to extract the current line and module being inspected."
2296 (defvar python-pdbtrack-tracked-buffer nil
2297 "Variable containing the value of the current tracked buffer.
2298 Never set this variable directly, use
2299 `python-pdbtrack-set-tracked-buffer' instead.")
2301 (defvar python-pdbtrack-buffers-to-kill nil
2302 "List of buffers to be deleted after tracking finishes.")
2304 (defun python-pdbtrack-set-tracked-buffer (file-name)
2305 "Set the buffer for FILE-NAME as the tracked buffer.
2306 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2307 Returns the tracked buffer."
2308 (let ((file-buffer (get-file-buffer file-name
)))
2310 (setq python-pdbtrack-tracked-buffer file-buffer
)
2311 (setq file-buffer
(find-file-noselect file-name
))
2312 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
2313 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
2316 (defun python-pdbtrack-comint-output-filter-function (output)
2317 "Move overlay arrow to current pdb line in tracked buffer.
2318 Argument OUTPUT is a string with the output from the comint process."
2319 (when (and python-pdbtrack-activate
(not (string= output
"")))
2320 (let* ((full-output (ansi-color-filter-apply
2321 (buffer-substring comint-last-input-end
(point-max))))
2325 (insert full-output
)
2326 (goto-char (point-min))
2327 ;; OK, this sucked but now it became a cool hack. The
2328 ;; stacktrace information normally is on the first line
2329 ;; but in some cases (like when doing a step-in) it is
2331 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp
)
2334 (looking-at python-pdbtrack-stacktrace-info-regexp
)))
2335 (setq line-number
(string-to-number
2336 (match-string-no-properties 2)))
2337 (match-string-no-properties 1)))))
2338 (if (and file-name line-number
)
2339 (let* ((tracked-buffer
2340 (python-pdbtrack-set-tracked-buffer file-name
))
2341 (shell-buffer (current-buffer))
2342 (tracked-buffer-window (get-buffer-window tracked-buffer
))
2343 (tracked-buffer-line-pos))
2344 (with-current-buffer tracked-buffer
2345 (set (make-local-variable 'overlay-arrow-string
) "=>")
2346 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
2347 (setq tracked-buffer-line-pos
(progn
2348 (goto-char (point-min))
2349 (forward-line (1- line-number
))
2351 (when tracked-buffer-window
2353 tracked-buffer-window tracked-buffer-line-pos
))
2354 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
2355 (pop-to-buffer tracked-buffer
)
2356 (switch-to-buffer-other-window shell-buffer
))
2357 (when python-pdbtrack-tracked-buffer
2358 (with-current-buffer python-pdbtrack-tracked-buffer
2359 (set-marker overlay-arrow-position nil
))
2360 (mapc #'(lambda (buffer)
2361 (ignore-errors (kill-buffer buffer
)))
2362 python-pdbtrack-buffers-to-kill
)
2363 (setq python-pdbtrack-tracked-buffer nil
2364 python-pdbtrack-buffers-to-kill nil
)))))
2368 ;;; Symbol completion
2370 (defun python-completion-complete-at-point ()
2371 "Complete current symbol at point.
2372 For this to work the best as possible you should call
2373 `python-shell-send-buffer' from time to time so context in
2374 inferior python process is updated properly."
2375 (let ((process (python-shell-get-process)))
2377 (error "Completion needs an inferior Python process running")
2378 (python-shell-completion-complete-at-point process
))))
2380 (add-to-list 'debug-ignored-errors
2381 "^Completion needs an inferior Python process running.")
2386 (defcustom python-fill-comment-function
'python-fill-comment
2387 "Function to fill comments.
2388 This is the function used by `python-fill-paragraph' to
2393 (defcustom python-fill-string-function
'python-fill-string
2394 "Function to fill strings.
2395 This is the function used by `python-fill-paragraph' to
2400 (defcustom python-fill-decorator-function
'python-fill-decorator
2401 "Function to fill decorators.
2402 This is the function used by `python-fill-paragraph' to
2407 (defcustom python-fill-paren-function
'python-fill-paren
2408 "Function to fill parens.
2409 This is the function used by `python-fill-paragraph' to
2414 (defcustom python-fill-docstring-style
'pep-257
2415 "Style used to fill docstrings.
2416 This affects `python-fill-string' behavior with regards to
2417 triple quotes positioning.
2419 Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2420 SYMMETRIC, and NIL. A value of NIL won't care about quotes
2421 position and will treat docstrings a normal string, any other
2422 value may result in one of the following docstring styles:
2427 Process foo, return bar.
2431 Process foo, return bar.
2433 If processing fails throw ProcessingError.
2438 \"\"\"Process foo, return bar.\"\"\"
2441 Process foo, return bar.
2443 If processing fails throw ProcessingError.
2449 \"\"\"Process foo, return bar.\"\"\"
2451 \"\"\"Process foo, return bar.
2453 If processing fails throw ProcessingError.
2459 \"\"\"Process foo, return bar.\"\"\"
2461 \"\"\"Process foo, return bar.
2463 If processing fails throw ProcessingError.
2468 \"\"\"Process foo, return bar.\"\"\"
2471 Process foo, return bar.
2473 If processing fails throw ProcessingError.
2476 (const :tag
"Don't format docstrings" nil
)
2477 (const :tag
"Django's coding standards style." django
)
2478 (const :tag
"One newline and start and Two at end style." onetwo
)
2479 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
2480 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
2481 (const :tag
"Symmetric style." symmetric
))
2484 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
2486 (defun python-fill-paragraph (&optional justify
)
2487 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2488 If any of the current line is in or at the end of a multi-line string,
2489 fill the string or the paragraph of it that point is in, preserving
2490 the string's indentation.
2491 Optional argument JUSTIFY defines if the paragraph should be justified."
2496 ((python-syntax-context 'comment
)
2497 (funcall python-fill-comment-function justify
))
2498 ;; Strings/Docstrings
2499 ((save-excursion (or (python-syntax-context 'string
)
2500 (equal (string-to-syntax "|")
2501 (syntax-after (point)))))
2502 (funcall python-fill-string-function justify
))
2504 ((equal (char-after (save-excursion
2505 (python-nav-beginning-of-statement))) ?
@)
2506 (funcall python-fill-decorator-function justify
))
2508 ((or (python-syntax-context 'paren
)
2509 (looking-at (python-rx open-paren
))
2511 (skip-syntax-forward "^(" (line-end-position))
2512 (looking-at (python-rx open-paren
))))
2513 (funcall python-fill-paren-function justify
))
2516 (defun python-fill-comment (&optional justify
)
2517 "Comment fill function for `python-fill-paragraph'.
2518 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2519 (fill-comment-paragraph justify
))
2521 (defun python-fill-string (&optional justify
)
2522 "String fill function for `python-fill-paragraph'.
2523 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2524 (let* ((marker (point-marker))
2528 (or (python-syntax-context 'string
)
2529 (and (equal (string-to-syntax "|")
2530 (syntax-after (point)))
2532 (num-quotes (python-syntax-count-quotes
2533 (char-after str-start-pos
) str-start-pos
))
2536 (goto-char (+ str-start-pos num-quotes
))
2537 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
2538 (goto-char (point-max)))
2541 ;; Docstring styles may vary for oneliners and multi-liners.
2542 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
2544 (pcase python-fill-docstring-style
2545 ;; delimiters-style is a cons cell with the form
2546 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2547 ;; is NIL means to not add any newlines for start or end
2548 ;; of docstring. See `python-fill-docstring-style' for a
2549 ;; graphic idea of each style.
2550 (`django
(cons 1 1))
2551 (`onetwo
(and multi-line-p
(cons 1 2)))
2552 (`pep-257
(and multi-line-p
(cons nil
2)))
2553 (`pep-257-nn
(and multi-line-p
(cons nil
1)))
2554 (`symmetric
(and multi-line-p
(cons 1 1)))))
2555 (docstring-p (save-excursion
2556 ;; Consider docstrings those strings which
2557 ;; start on a line by themselves.
2558 (python-nav-beginning-of-statement)
2559 (and (= (point) str-start-pos
))))
2560 (fill-paragraph-function))
2562 (narrow-to-region str-start-pos str-end-pos
)
2563 (fill-paragraph justify
))
2565 (when (and docstring-p python-fill-docstring-style
)
2566 ;; Add the number of newlines indicated by the selected style
2567 ;; at the start of the docstring.
2568 (goto-char (+ str-start-pos num-quotes
))
2569 (delete-region (point) (progn
2570 (skip-syntax-forward "> ")
2572 (and (car delimiters-style
)
2573 (or (newline (car delimiters-style
)) t
)
2574 ;; Indent only if a newline is added.
2575 (indent-according-to-mode))
2576 ;; Add the number of newlines indicated by the selected style
2577 ;; at the end of the docstring.
2578 (goto-char (if (not (= str-end-pos
(point-max)))
2579 (- str-end-pos num-quotes
)
2581 (delete-region (point) (progn
2582 (skip-syntax-backward "> ")
2584 (and (cdr delimiters-style
)
2585 ;; Add newlines only if string ends.
2586 (not (= str-end-pos
(point-max)))
2587 (or (newline (cdr delimiters-style
)) t
)
2588 ;; Again indent only if a newline is added.
2589 (indent-according-to-mode))))) t
)
2591 (defun python-fill-decorator (&optional justify
)
2592 "Decorator fill function for `python-fill-paragraph'.
2593 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2596 (defun python-fill-paren (&optional justify
)
2597 "Paren fill function for `python-fill-paragraph'.
2598 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2600 (narrow-to-region (progn
2601 (while (python-syntax-context 'paren
)
2602 (goto-char (1- (point-marker))))
2604 (line-beginning-position))
2606 (when (not (python-syntax-context 'paren
))
2608 (when (not (python-syntax-context 'paren
))
2609 (skip-syntax-backward "^)")))
2610 (while (python-syntax-context 'paren
)
2611 (goto-char (1+ (point-marker))))
2613 (let ((paragraph-start "\f\\|[ \t]*$")
2614 (paragraph-separate ",")
2615 (fill-paragraph-function))
2616 (goto-char (point-min))
2617 (fill-paragraph justify
))
2620 (python-indent-line)
2621 (goto-char (line-end-position)))) t
)
2626 (defcustom python-skeleton-autoinsert nil
2627 "Non-nil means template skeletons will be automagically inserted.
2628 This happens when pressing \"if<SPACE>\", for example, to prompt for
2634 (define-obsolete-variable-alias
2635 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
2637 (defvar python-skeleton-available
'()
2638 "Internal list of available skeletons.")
2640 (define-abbrev-table 'python-mode-abbrev-table
()
2641 "Abbrev table for Python mode."
2643 ;; Allow / inside abbrevs.
2644 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2645 ;; Only expand in code.
2646 :enable-function
(lambda ()
2648 (not (python-syntax-comment-or-string-p))
2649 python-skeleton-autoinsert
)))
2651 (defmacro python-skeleton-define
(name doc
&rest skel
)
2652 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2653 The skeleton will be bound to python-skeleton-NAME and will
2654 be added to `python-mode-abbrev-table'."
2655 (declare (indent 2))
2656 (let* ((name (symbol-name name
))
2657 (function-name (intern (concat "python-skeleton-" name
))))
2659 (define-abbrev python-mode-abbrev-table
,name
"" ',function-name
2661 (setq python-skeleton-available
2662 (cons ',function-name python-skeleton-available
))
2663 (define-skeleton ,function-name
2665 (format "Insert %s statement." name
))
2668 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
2669 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2670 The skeleton will be bound to python-skeleton-NAME."
2671 (declare (indent 2))
2672 (let* ((name (symbol-name name
))
2673 (function-name (intern (concat "python-skeleton--" name
)))
2675 "Add '%s' clause? " name
)))
2678 `(< ,(format "%s:" name
) \n \n
2680 `(define-skeleton ,function-name
2682 (format "Auxiliary skeleton for %s statement." name
))
2684 (unless (y-or-n-p ,msg
)
2688 (python-define-auxiliary-skeleton else nil
)
2690 (python-define-auxiliary-skeleton except nil
)
2692 (python-define-auxiliary-skeleton finally nil
)
2694 (python-skeleton-define if nil
2698 ("other condition, %s: "
2702 '(python-skeleton--else) | ^
)
2704 (python-skeleton-define while nil
2708 '(python-skeleton--else) | ^
)
2710 (python-skeleton-define for nil
2714 '(python-skeleton--else) | ^
)
2716 (python-skeleton-define try nil
2722 "except " str
":" \n
2725 '(python-skeleton--except)
2726 '(python-skeleton--else)
2727 '(python-skeleton--finally) | ^
)
2729 (python-skeleton-define def nil
2731 "def " str
"(" ("Parameter, %s: "
2732 (unless (equal ?\
( (char-before)) ", ")
2734 "\"\"\"" -
"\"\"\"" \n
2737 (python-skeleton-define class nil
2739 "class " str
"(" ("Inheritance, %s: "
2740 (unless (equal ?\
( (char-before)) ", ")
2744 "\"\"\"" -
"\"\"\"" \n
2747 (defun python-skeleton-add-menu-items ()
2748 "Add menu items to Python->Skeletons menu."
2749 (let ((skeletons (sort python-skeleton-available
'string
<))
2751 (dolist (skeleton skeletons
)
2753 nil
'("Python" "Skeletons")
2755 "Insert %s" (nth 2 (split-string (symbol-name skeleton
) "-")))
2760 (defcustom python-ffap-setup-code
2761 "def __FFAP_get_module_path(module):
2764 path = __import__(module).__file__
2765 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2770 "Python code to get a module path."
2774 (defcustom python-ffap-string-code
2775 "__FFAP_get_module_path('''%s''')\n"
2776 "Python code used to get a string with the path of a module."
2780 (defun python-ffap-module-path (module)
2781 "Function for `ffap-alist' to return path for MODULE."
2783 (and (eq major-mode
'inferior-python-mode
)
2784 (get-buffer-process (current-buffer)))
2785 (python-shell-get-process))))
2789 (python-shell-send-string-no-output
2790 (format python-ffap-string-code module
) process
)))
2792 (substring-no-properties module-file
1 -
1))))))
2794 (eval-after-load "ffap"
2796 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
2797 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
2802 (defcustom python-check-command
2804 "Command used to check a Python file."
2808 (defcustom python-check-buffer-name
2809 "*Python check: %s*"
2810 "Buffer name used for check commands."
2814 (defvar python-check-custom-command nil
2817 (defun python-check (command)
2818 "Check a Python file (default current buffer's file).
2819 Runs COMMAND, a shell command, as if by `compile'. See
2820 `python-check-command' for the default."
2822 (list (read-string "Check command: "
2823 (or python-check-custom-command
2824 (concat python-check-command
" "
2825 (shell-quote-argument
2827 (let ((name (buffer-file-name)))
2829 (file-name-nondirectory name
)))
2831 (setq python-check-custom-command command
)
2832 (save-some-buffers (not compilation-ask-about-save
) nil
)
2833 (let ((process-environment (python-shell-calculate-process-environment))
2834 (exec-path (python-shell-calculate-exec-path)))
2835 (compilation-start command nil
2837 (format python-check-buffer-name command
)))))
2842 (defcustom python-eldoc-setup-code
2843 "def __PYDOC_get_help(obj):
2846 if hasattr(obj, 'startswith'):
2847 obj = eval(obj, globals())
2848 doc = inspect.getdoc(obj)
2849 if not doc and callable(obj):
2851 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2852 target = obj.__init__
2858 args = inspect.formatargspec(
2859 *inspect.getargspec(target)
2862 doc = '{objtype} {name}{args}'.format(
2863 objtype=objtype, name=name, args=args
2866 doc = doc.splitlines()[0]
2873 "Python code to setup documentation retrieval."
2877 (defcustom python-eldoc-string-code
2878 "__PYDOC_get_help('''%s''')\n"
2879 "Python code used to get a string with the documentation of an object."
2883 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
2884 "Internal implementation to get documentation at point.
2885 If not FORCE-INPUT is passed then what
2886 `python-info-current-symbol' returns will be used. If not
2887 FORCE-PROCESS is passed what `python-shell-get-process' returns
2889 (let ((process (or force-process
(python-shell-get-process))))
2891 (error "Eldoc needs an inferior Python process running")
2892 (let ((input (or force-input
2893 (python-info-current-symbol t
))))
2895 (python-shell-send-string-no-output
2896 (format python-eldoc-string-code input
)
2899 (defun python-eldoc-function ()
2900 "`eldoc-documentation-function' for Python.
2901 For this to work the best as possible you should call
2902 `python-shell-send-buffer' from time to time so context in
2903 inferior python process is updated properly."
2904 (python-eldoc--get-doc-at-point))
2906 (defun python-eldoc-at-point (symbol)
2907 "Get help on SYMBOL using `help'.
2908 Interactively, prompt for symbol."
2910 (let ((symbol (python-info-current-symbol t
))
2911 (enable-recursive-minibuffers t
))
2912 (list (read-string (if symbol
2913 (format "Describe symbol (default %s): " symbol
)
2914 "Describe symbol: ")
2916 (message (python-eldoc--get-doc-at-point symbol
)))
2918 (add-to-list 'debug-ignored-errors
2919 "^Eldoc needs an inferior Python process running.")
2924 (defun python-imenu-prev-index-position ()
2925 "Python mode's `imenu-prev-index-position-function'."
2927 (while (and (setq found
2928 (re-search-backward python-nav-beginning-of-defun-regexp nil t
))
2929 (not (python-info-looking-at-beginning-of-defun))))
2931 (python-info-looking-at-beginning-of-defun)
2932 (python-info-current-defun))))
2937 (defun python-info-current-defun (&optional include-type
)
2938 "Return name of surrounding function with Python compatible dotty syntax.
2939 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2940 This function is compatible to be used as
2941 `add-log-current-defun-function' since it returns nil if point is
2942 not inside a defun."
2948 (starting-indentation
2951 (python-nav-beginning-of-defun 1)
2952 ;; This extra number is just for checking code
2953 ;; against indentation to work well on first run.
2954 (+ (current-indentation) 4))))
2955 (starting-point (point)))
2956 ;; Check point is inside a defun.
2957 (when (and starting-indentation
2960 (python-nav-end-of-defun)
2963 (while (python-nav-beginning-of-defun 1)
2964 (when (< (current-indentation) starting-indentation
)
2965 (setq starting-indentation
(current-indentation))
2968 (if (not include-type
)
2969 (match-string-no-properties 1)
2970 (mapconcat 'identity
2972 (match-string-no-properties 0)) " "))
2974 (and (= (current-indentation) 0) (throw 'exit t
)))))
2976 (mapconcat (lambda (string) string
) names
"."))))))
2978 (defun python-info-current-symbol (&optional replace-self
)
2979 "Return current symbol using dotty syntax.
2980 With optional argument REPLACE-SELF convert \"self\" to current
2983 (and (not (python-syntax-comment-or-string-p))
2984 (with-syntax-table python-dotty-syntax-table
2985 (let ((sym (symbol-at-point)))
2987 (substring-no-properties (symbol-name sym
))))))))
2989 (if (not replace-self
)
2991 (let ((current-defun (python-info-current-defun)))
2992 (if (not current-defun
)
2994 (replace-regexp-in-string
2995 (python-rx line-start word-start
"self" word-end ?.
)
2997 (mapconcat 'identity
2998 (butlast (split-string current-defun
"\\."))
3002 (defun python-info-statement-starts-block-p ()
3003 "Return non-nil if current statement opens a block."
3005 (python-nav-beginning-of-statement)
3006 (looking-at (python-rx block-start
))))
3008 (defun python-info-statement-ends-block-p ()
3009 "Return non-nil if point is at end of block."
3010 (let ((end-of-block-pos (save-excursion
3011 (python-nav-end-of-block)))
3012 (end-of-statement-pos (save-excursion
3013 (python-nav-end-of-statement))))
3014 (and end-of-block-pos end-of-statement-pos
3015 (= end-of-block-pos end-of-statement-pos
))))
3017 (defun python-info-beginning-of-statement-p ()
3018 "Return non-nil if point is at beginning of statement."
3019 (= (point) (save-excursion
3020 (python-nav-beginning-of-statement)
3023 (defun python-info-end-of-statement-p ()
3024 "Return non-nil if point is at end of statement."
3025 (= (point) (save-excursion
3026 (python-nav-end-of-statement)
3029 (defun python-info-beginning-of-block-p ()
3030 "Return non-nil if point is at beginning of block."
3031 (and (python-info-beginning-of-statement-p)
3032 (python-info-statement-starts-block-p)))
3034 (defun python-info-end-of-block-p ()
3035 "Return non-nil if point is at end of block."
3036 (and (python-info-end-of-statement-p)
3037 (python-info-statement-ends-block-p)))
3039 (defun python-info-closing-block ()
3040 "Return the point of the block the current line closes."
3041 (let ((closing-word (save-excursion
3042 (back-to-indentation)
3044 (indentation (current-indentation)))
3045 (when (member closing-word python-indent-dedenters
)
3048 (while (and (> (current-indentation) indentation
)
3050 (not (back-to-indentation))
3052 (back-to-indentation)
3054 ((not (equal indentation
(current-indentation))) nil
)
3055 ((string= closing-word
"elif")
3056 (when (member (current-word) '("if" "elif"))
3058 ((string= closing-word
"else")
3059 (when (member (current-word) '("if" "elif" "except" "for" "while"))
3061 ((string= closing-word
"except")
3062 (when (member (current-word) '("try"))
3064 ((string= closing-word
"finally")
3065 (when (member (current-word) '("except" "else"))
3066 (point-marker))))))))
3068 (defun python-info-closing-block-message (&optional closing-block-point
)
3069 "Message the contents of the block the current line closes.
3070 With optional argument CLOSING-BLOCK-POINT use that instead of
3071 recalculating it calling `python-info-closing-block'."
3072 (let ((point (or closing-block-point
(python-info-closing-block))))
3076 (message "Closes %s" (save-excursion
3078 (back-to-indentation)
3080 (point) (line-end-position))))))))
3082 (defun python-info-line-ends-backslash-p (&optional line-number
)
3083 "Return non-nil if current line ends with backslash.
3084 With optional argument LINE-NUMBER, check that line instead."
3089 (goto-char line-number
))
3090 (while (and (not (eobp))
3091 (goto-char (line-end-position))
3092 (python-syntax-context 'paren
)
3093 (not (equal (char-before (point)) ?
\\)))
3095 (when (equal (char-before) ?
\\)
3098 (defun python-info-beginning-of-backslash (&optional line-number
)
3099 "Return the point where the backslashed line start.
3100 Optional argument LINE-NUMBER forces the line number to check against."
3105 (goto-char line-number
))
3106 (when (python-info-line-ends-backslash-p)
3107 (while (save-excursion
3108 (goto-char (line-beginning-position))
3109 (python-syntax-context 'paren
))
3111 (back-to-indentation)
3114 (defun python-info-continuation-line-p ()
3115 "Check if current line is continuation of another.
3116 When current line is continuation of another return the point
3117 where the continued line ends."
3121 (let* ((context-type (progn
3122 (back-to-indentation)
3123 (python-syntax-context-type)))
3124 (line-start (line-number-at-pos))
3125 (context-start (when context-type
3126 (python-syntax-context context-type
))))
3127 (cond ((equal context-type
'paren
)
3128 ;; Lines inside a paren are always a continuation line
3129 ;; (except the first one).
3130 (python-util-forward-comment -
1)
3132 ((member context-type
'(string comment
))
3133 ;; move forward an roll again
3134 (goto-char context-start
)
3135 (python-util-forward-comment)
3136 (python-info-continuation-line-p))
3138 ;; Not within a paren, string or comment, the only way
3139 ;; we are dealing with a continuation line is that
3140 ;; previous line contains a backslash, and this can
3141 ;; only be the previous line from current
3142 (back-to-indentation)
3143 (python-util-forward-comment -
1)
3144 (when (and (equal (1- line-start
) (line-number-at-pos))
3145 (python-info-line-ends-backslash-p))
3146 (point-marker))))))))
3148 (defun python-info-block-continuation-line-p ()
3149 "Return non-nil if current line is a continuation of a block."
3151 (when (python-info-continuation-line-p)
3153 (back-to-indentation)
3154 (when (looking-at (python-rx block-start
))
3157 (defun python-info-assignment-continuation-line-p ()
3158 "Check if current line is a continuation of an assignment.
3159 When current line is continuation of another with an assignment
3160 return the point of the first non-blank character after the
3163 (when (python-info-continuation-line-p)
3165 (back-to-indentation)
3166 (when (and (not (looking-at (python-rx block-start
)))
3167 (and (re-search-forward (python-rx not-simple-operator
3169 not-simple-operator
)
3170 (line-end-position) t
)
3171 (not (python-syntax-context-type))))
3172 (skip-syntax-forward "\s")
3175 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
3176 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3177 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
3179 (beginning-of-line 1)
3180 (looking-at python-nav-beginning-of-defun-regexp
))))
3182 (defun python-info-current-line-comment-p ()
3183 "Check if current line is a comment line."
3184 (char-equal (or (char-after (+ (point) (current-indentation))) ?_
) ?
#))
3186 (defun python-info-current-line-empty-p ()
3187 "Check if current line is empty, ignoring whitespace."
3189 (beginning-of-line 1)
3191 (python-rx line-start
(* whitespace
)
3192 (group (* not-newline
))
3193 (* whitespace
) line-end
))
3194 (string-equal "" (match-string-no-properties 1))))
3197 ;;; Utility functions
3199 (defun python-util-position (item seq
)
3200 "Find the first occurrence of ITEM in SEQ.
3201 Return the index of the matching item, or nil if not found."
3202 (let ((member-result (member item seq
)))
3204 (- (length seq
) (length member-result
)))))
3206 ;; Stolen from org-mode
3207 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
3208 "Clone local variables from FROM-BUFFER.
3209 Optional argument REGEXP selects variables to clone and defaults
3213 (and (symbolp (car pair
))
3214 (string-match (or regexp
"^python-")
3215 (symbol-name (car pair
)))
3216 (set (make-local-variable (car pair
))
3218 (buffer-local-variables from-buffer
)))
3220 (defun python-util-forward-comment (&optional direction
)
3221 "Python mode specific version of `forward-comment'.
3222 Optional argument DIRECTION defines the direction to move to."
3223 (let ((comment-start (python-syntax-context 'comment
))
3224 (factor (if (< (or direction
0) 0)
3228 (goto-char comment-start
))
3229 (forward-comment factor
)))
3233 (define-derived-mode python-mode prog-mode
"Python"
3234 "Major mode for editing Python files.
3237 Entry to this mode calls the value of `python-mode-hook'
3238 if that value is non-nil."
3239 (set (make-local-variable 'tab-width
) 8)
3240 (set (make-local-variable 'indent-tabs-mode
) nil
)
3242 (set (make-local-variable 'comment-start
) "# ")
3243 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
3245 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3246 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3248 (set (make-local-variable 'forward-sexp-function
)
3249 'python-nav-forward-sexp
)
3251 (set (make-local-variable 'font-lock-defaults
)
3252 '(python-font-lock-keywords nil nil nil nil
))
3254 (set (make-local-variable 'syntax-propertize-function
)
3255 python-syntax-propertize-function
)
3257 (set (make-local-variable 'indent-line-function
)
3258 #'python-indent-line-function
)
3259 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
3261 (set (make-local-variable 'paragraph-start
) "\\s-*$")
3262 (set (make-local-variable 'fill-paragraph-function
)
3263 'python-fill-paragraph
)
3265 (set (make-local-variable 'beginning-of-defun-function
)
3266 #'python-nav-beginning-of-defun
)
3267 (set (make-local-variable 'end-of-defun-function
)
3268 #'python-nav-end-of-defun
)
3270 (add-hook 'completion-at-point-functions
3271 'python-completion-complete-at-point nil
'local
)
3273 (add-hook 'post-self-insert-hook
3274 'python-indent-post-self-insert-function nil
'local
)
3276 (set (make-local-variable 'imenu-extract-index-name-function
)
3277 #'python-info-current-defun
)
3279 (set (make-local-variable 'imenu-prev-index-position-function
)
3280 #'python-imenu-prev-index-position
)
3282 (set (make-local-variable 'add-log-current-defun-function
)
3283 #'python-info-current-defun
)
3285 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
3287 (set (make-local-variable 'skeleton-further-elements
)
3289 (< '(backward-delete-char-untabify (min python-indent-offset
3291 (^
'(- (1+ (current-indentation))))))
3293 (set (make-local-variable 'eldoc-documentation-function
)
3294 #'python-eldoc-function
)
3296 (add-to-list 'hs-special-modes-alist
3297 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
3299 (python-nav-end-of-defun)) nil
))
3301 (set (make-local-variable 'mode-require-final-newline
) t
)
3303 (set (make-local-variable 'outline-regexp
)
3304 (python-rx (* space
) block-start
))
3305 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
3306 (set (make-local-variable 'outline-level
)
3308 "`outline-level' function for Python mode."
3309 (1+ (/ (current-indentation) python-indent-offset
))))
3311 (python-skeleton-add-menu-items)
3313 (make-local-variable 'python-shell-internal-buffer
)
3315 (when python-indent-guess-indent-offset
3316 (python-indent-guess-indent-offset)))
3323 ;; indent-tabs-mode: nil
3326 ;;; python.el ends here