1 ;;; python.el --- Python's flying circus support for Emacs
3 ;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
10 ;; Keywords: languages
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published
16 ;; by the Free Software Foundation, either version 3 of the License,
17 ;; or (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful, but
20 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 ;; General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; Major mode for editing Python files with some fontification and
30 ;; indentation bits extracted from original Dave Love's python.el
31 ;; found in GNU/Emacs.
33 ;; Implements Syntax highlighting, Indentation, Movement, Shell
34 ;; interaction, Shell completion, Shell virtualenv support, Pdb
35 ;; tracking, Symbol completion, Skeletons, FFAP, Code Check, Eldoc,
38 ;; Syntax highlighting: Fontification of code is provided and supports
39 ;; python's triple quoted strings properly.
41 ;; Indentation: Automatic indentation with indentation cycling is
42 ;; provided, it allows you to navigate different available levels of
43 ;; indentation by hitting <tab> several times. Also when inserting a
44 ;; colon the `python-indent-electric-colon' command is invoked and
45 ;; causes the current line to be dedented automatically if needed.
47 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
48 ;; properly implemented. There are also specialized
49 ;; `forward-sentence' and `backward-sentence' replacements called
50 ;; `python-nav-forward-block', `python-nav-backward-block'
51 ;; respectively which navigate between beginning of blocks of code.
52 ;; Extra functions `python-nav-forward-statement',
53 ;; `python-nav-backward-statement',
54 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
55 ;; `python-nav-beginning-of-block' and `python-nav-end-of-block' are
56 ;; included but no bound to any key. At last but not least the
57 ;; specialized `python-nav-forward-sexp' allows easy
58 ;; navigation between code blocks.
60 ;; Shell interaction: is provided and allows you to execute easily any
61 ;; block of code of your current buffer in an inferior Python process.
63 ;; Shell completion: hitting tab will try to complete the current
64 ;; word. Shell completion is implemented in a manner that if you
65 ;; change the `python-shell-interpreter' to any other (for example
66 ;; IPython) it should be easy to integrate another way to calculate
67 ;; completions. You just need to specify your custom
68 ;; `python-shell-completion-setup-code' and
69 ;; `python-shell-completion-string-code'.
71 ;; Here is a complete example of the settings you would use for
75 ;; python-shell-interpreter "ipython"
76 ;; python-shell-interpreter-args ""
77 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
78 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
79 ;; python-shell-completion-setup-code
80 ;; "from IPython.core.completerlib import module_completion"
81 ;; python-shell-completion-module-string-code
82 ;; "';'.join(module_completion('''%s'''))\n"
83 ;; python-shell-completion-string-code
84 ;; "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
86 ;; For iPython 0.10 everything would be the same except for
87 ;; `python-shell-completion-string-code' and
88 ;; `python-shell-completion-module-string-code':
90 ;; (setq python-shell-completion-string-code
91 ;; "';'.join(__IP.complete('''%s'''))\n"
92 ;; python-shell-completion-module-string-code "")
94 ;; Unfortunately running iPython on Windows needs some more tweaking.
95 ;; The way you must set `python-shell-interpreter' and
96 ;; `python-shell-interpreter-args' is as follows:
99 ;; python-shell-interpreter "C:\\Python27\\python.exe"
100 ;; python-shell-interpreter-args
101 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
103 ;; That will spawn the iPython process correctly (Of course you need
104 ;; to modify the paths according to your system).
106 ;; Please note that the default completion system depends on the
107 ;; readline module, so if you are using some Operating System that
108 ;; bundles Python without it (like Windows) just install the
109 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
110 ;; you should be good to go.
112 ;; Shell virtualenv support: The shell also contains support for
113 ;; virtualenvs and other special environment modifications thanks to
114 ;; `python-shell-process-environment' and `python-shell-exec-path'.
115 ;; These two variables allows you to modify execution paths and
116 ;; environment variables to make easy for you to setup virtualenv rules
117 ;; or behavior modifications when running shells. Here is an example
118 ;; of how to make shell processes to be run using the /path/to/env/
121 ;; (setq python-shell-process-environment
123 ;; (format "PATH=%s" (mapconcat
126 ;; (cons (getenv "PATH")
127 ;; '("/path/to/env/bin/")))
129 ;; "VIRTUAL_ENV=/path/to/env/"))
130 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
132 ;; Since the above is cumbersome and can be programmatically
133 ;; calculated, the variable `python-shell-virtualenv-path' is
134 ;; provided. When this variable is set with the path of the
135 ;; virtualenv to use, `process-environment' and `exec-path' get proper
136 ;; values in order to run shells inside the specified virtualenv. So
137 ;; the following will achieve the same as the previous example:
139 ;; (setq python-shell-virtualenv-path "/path/to/env/")
141 ;; Also the `python-shell-extra-pythonpaths' variable have been
142 ;; introduced as simple way of adding paths to the PYTHONPATH without
143 ;; affecting existing values.
145 ;; Pdb tracking: when you execute a block of code that contains some
146 ;; call to pdb (or ipdb) it will prompt the block of code and will
147 ;; follow the execution of pdb marking the current line with an arrow.
149 ;; Symbol completion: you can complete the symbol at point. It uses
150 ;; the shell completion in background so you should run
151 ;; `python-shell-send-buffer' from time to time to get better results.
153 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
154 ;; def, for, if, try and while. These skeletons are integrated with
155 ;; dabbrev. If you have `dabbrev-mode' activated and
156 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
157 ;; the name of any of those defined and hit SPC, they will be
158 ;; automatically expanded.
160 ;; FFAP: You can find the filename for a given module when using ffap
161 ;; out of the box. This feature needs an inferior python shell
164 ;; Code check: Check the current file for errors with `python-check'
165 ;; using the program defined in `python-check-command'.
167 ;; Eldoc: returns documentation for object at point by using the
168 ;; inferior python subprocess to inspect its documentation. As you
169 ;; might guessed you should run `python-shell-send-buffer' from time
170 ;; to time to get better results too.
172 ;; imenu: This mode supports imenu in its most basic form, letting it
173 ;; build the necessary alist via `imenu-default-create-index-function'
174 ;; by having set `imenu-extract-index-name-function' to
175 ;; `python-info-current-defun'.
177 ;; If you used python-mode.el you probably will miss auto-indentation
178 ;; when inserting newlines. To achieve the same behavior you have
181 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
183 ;; 2) Add the following hook in your .emacs:
185 ;; (add-hook 'python-mode-hook
187 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
189 ;; I'd recommend the first one since you'll get the same behavior for
190 ;; all modes out-of-the-box.
194 ;; Add this to your .emacs:
196 ;; (add-to-list 'load-path "/folder/containing/file")
203 (require 'ansi-color
)
208 ;; Avoid compiler warnings
209 (defvar view-return-to-alist
)
210 (defvar compilation-error-regexp-alist
)
211 (defvar outline-heading-end-regexp
))
213 (autoload 'comint-mode
"comint")
216 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
218 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python") 'python-mode
))
221 "Python Language's flying circus support for Emacs."
224 :link
'(emacs-commentary-link "python"))
229 (defvar python-mode-map
230 (let ((map (make-sparse-keymap)))
232 (substitute-key-definition 'backward-sentence
233 'python-nav-backward-block
235 (substitute-key-definition 'forward-sentence
236 'python-nav-forward-block
238 (define-key map
"\C-c\C-j" 'imenu
)
240 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
241 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
242 (define-key map
"\C-c<" 'python-indent-shift-left
)
243 (define-key map
"\C-c>" 'python-indent-shift-right
)
244 (define-key map
":" 'python-indent-electric-colon
)
246 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
247 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
248 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
249 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
250 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
251 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
253 (define-key map
"\C-c\C-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 "Additional Python specific sexps for `python-rx'"))
343 (defmacro python-rx
(&rest regexps
)
344 "Python mode specialized rx macro.
345 This variant of `rx' supports common python named REGEXPS."
346 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
347 (cond ((null regexps
)
350 (rx-to-string `(and ,@regexps
) t
))
352 (rx-to-string (car regexps
) t
)))))
355 ;;; Font-lock and syntax
357 (defun python-syntax-context (type &optional syntax-ppss
)
358 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
359 TYPE can be `comment', `string' or `paren'. It returns the start
360 character address of the specified TYPE."
361 (let ((ppss (or syntax-ppss
(syntax-ppss))))
363 (comment (and (nth 4 ppss
) (nth 8 ppss
)))
364 (string (and (not (nth 4 ppss
)) (nth 8 ppss
)))
368 (defun python-syntax-context-type (&optional syntax-ppss
)
369 "Return the context type using SYNTAX-PPSS.
370 The type returned can be `comment', `string' or `paren'."
371 (let ((ppss (or syntax-ppss
(syntax-ppss))))
373 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
374 ((nth 1 ppss
) 'paren
))))
376 (defsubst python-syntax-comment-or-string-p
()
377 "Return non-nil if point is inside 'comment or 'string."
378 (nth 8 (syntax-ppss)))
380 (define-obsolete-function-alias
381 'python-info-ppss-context
#'python-syntax-context
"24.3")
383 (define-obsolete-function-alias
384 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
386 (define-obsolete-function-alias
387 'python-info-ppss-comment-or-string-p
388 #'python-syntax-comment-or-string-p
"24.3")
390 (defvar python-font-lock-keywords
394 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
395 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
396 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
401 ;; False, None, and True are listed as keywords on the Python 3
402 ;; documentation, but since they also qualify as constants they are
403 ;; fontified like that in order to keep font-lock consistent between
410 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
411 (1 font-lock-function-name-face
))
413 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
414 (1 font-lock-type-face
))
418 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
419 ;; copyright, license, credits, quit and exit are added by the site
420 ;; module and they are not intended to be used in programs
421 "copyright" "credits" "exit" "license" "quit")
422 symbol-end
) . font-lock-constant-face
)
424 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
425 (0+ "." (1+ (or word ?_
)))))
426 (1 font-lock-type-face
))
427 ;; Builtin Exceptions
430 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
431 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
432 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
433 "ImportError" "ImportWarning" "IndexError" "KeyError"
434 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
435 "NotImplementedError" "OSError" "OverflowError"
436 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
437 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
438 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
439 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
440 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
441 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
445 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
447 symbol-end
) . font-lock-type-face
)
451 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
452 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
453 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
454 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
455 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
456 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
457 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
458 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
461 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
462 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
465 "ascii" "bytearray" "bytes" "exec"
467 "__all__" "__doc__" "__name__" "__package__")
468 symbol-end
) . font-lock-builtin-face
)
470 ;; support for a = b = c = 5
472 (let ((re (python-rx (group (+ (any word ?. ?_
)))
473 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
474 assignment-operator
)))
475 (when (re-search-forward re limit t
)
476 (while (and (python-syntax-context 'paren
)
477 (re-search-forward re limit t
)))
478 (if (and (not (python-syntax-context 'paren
))
479 (not (equal (char-after (point-marker)) ?
=)))
481 (set-match-data nil
)))))
482 (1 font-lock-variable-name-face nil nil
))
483 ;; support for a, b, c = (1, 2, 3)
485 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
486 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
487 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
488 assignment-operator
)))
489 (when (and (re-search-forward re limit t
)
490 (goto-char (nth 3 (match-data))))
491 (while (and (python-syntax-context 'paren
)
492 (re-search-forward re limit t
))
493 (goto-char (nth 3 (match-data))))
494 (if (not (python-syntax-context 'paren
))
496 (set-match-data nil
)))))
497 (1 font-lock-variable-name-face nil nil
))))
499 (defconst python-syntax-propertize-function
500 (syntax-propertize-rules
502 ;; Match even number of backslashes.
503 (or (not (any ?
\\ ?
\' ?
\")) point
) (* ?
\\ ?
\\)
504 ;; Match single or triple quotes of any kind.
505 (group (or "\"" "\"\"\"" "'" "'''")))
506 (1 (ignore (python-syntax-stringify))))
508 ;; Match odd number of backslashes.
509 (or (not (any ?
\\)) point
) ?
\\ (* ?
\\ ?
\\)
510 ;; Followed by even number of equal quotes.
511 (group (or "\"\"" "\"\"\"\"" "''" "''''")))
512 (1 (ignore (python-syntax-stringify))))))
514 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
515 "Count number of quotes around point (max is 3).
516 QUOTE-CHAR is the quote char to count. Optional argument POINT is
517 the point where scan starts (defaults to current point) and LIMIT
518 is used to limit the scan."
521 (or (not limit
) (< (+ point i
) limit
))
522 (eq (char-after (+ point i
)) quote-char
))
526 (defun python-syntax-stringify ()
527 "Put `syntax-table' property correctly on single/triple quotes."
529 (let ((n (length (match-string-no-properties 1))))
530 ;; This corrects the quote count when matching odd number
531 ;; of backslashes followed by even number of quotes.
532 (or (and (= 1 (logand n
1)) n
) (1- n
))))
534 (backward-char num-quotes
)
536 (forward-char num-quotes
)))
537 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
538 (quote-starting-pos (- (point) num-quotes
))
539 (quote-ending-pos (point))
542 (python-syntax-count-quotes
543 (char-before) string-start quote-starting-pos
))))
544 (cond ((and string-start
(= num-closing-quotes
0))
545 ;; This set of quotes doesn't match the string starting
549 ;; This set of quotes delimit the start of a string.
550 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
551 'syntax-table
(string-to-syntax "|")))
552 ((= num-quotes num-closing-quotes
)
553 ;; This set of quotes delimit the end of a string.
554 (put-text-property (1- quote-ending-pos
) quote-ending-pos
555 'syntax-table
(string-to-syntax "|")))
556 ((> num-quotes num-closing-quotes
)
557 ;; This may only happen whenever a triple quote is closing
558 ;; a single quoted string. Add string delimiter syntax to
560 (put-text-property quote-starting-pos quote-ending-pos
561 'syntax-table
(string-to-syntax "|"))))))
563 (defvar python-mode-syntax-table
564 (let ((table (make-syntax-table)))
565 ;; Give punctuation syntax to ASCII that normally has symbol
566 ;; syntax or has word syntax and isn't a letter.
567 (let ((symbol (string-to-syntax "_"))
568 (sst (standard-syntax-table)))
571 (if (equal symbol
(aref sst i
))
572 (modify-syntax-entry i
"." table
)))))
573 (modify-syntax-entry ?$
"." table
)
574 (modify-syntax-entry ?%
"." table
)
576 (modify-syntax-entry ?
# "<" table
)
577 (modify-syntax-entry ?
\n ">" table
)
578 (modify-syntax-entry ?
' "\"" table
)
579 (modify-syntax-entry ?
` "$" table
)
581 "Syntax table for Python files.")
583 (defvar python-dotty-syntax-table
584 (let ((table (make-syntax-table python-mode-syntax-table
)))
585 (modify-syntax-entry ?.
"w" table
)
586 (modify-syntax-entry ?_
"w" table
)
588 "Dotty syntax table for Python files.
589 It makes underscores and dots word constituent chars.")
594 (defcustom python-indent-offset
4
595 "Default indentation offset for Python."
600 (defcustom python-indent-guess-indent-offset t
601 "Non-nil tells Python mode to guess `python-indent-offset' value."
606 (define-obsolete-variable-alias
607 'python-indent
'python-indent-offset
"24.3")
609 (define-obsolete-variable-alias
610 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
612 (defvar python-indent-current-level
0
613 "Current indentation level `python-indent-line-function' is using.")
615 (defvar python-indent-levels
'(0)
616 "Levels of indentation available for `python-indent-line-function'.")
618 (defvar python-indent-dedenters
'("else" "elif" "except" "finally")
619 "List of words that should be dedented.
620 These make `python-indent-calculate-indentation' subtract the value of
621 `python-indent-offset'.")
623 (defun python-indent-guess-indent-offset ()
624 "Guess and set `python-indent-offset' for the current buffer."
629 (goto-char (point-min))
631 (while (and (not block-end
)
633 (python-rx line-start block-start
) nil t
))
635 (not (python-syntax-context-type))
637 (goto-char (line-end-position))
638 (python-util-forward-comment -
1)
639 (if (equal (char-before) ?
:)
642 (when (python-info-block-continuation-line-p)
643 (while (and (python-info-continuation-line-p)
646 (python-util-forward-comment -
1)
647 (when (equal (char-before) ?
:)
649 (setq block-end
(point-marker))))
652 (goto-char block-end
)
653 (python-util-forward-comment)
654 (current-indentation))))
656 (setq python-indent-offset indentation
)
657 (message "Can't guess python-indent-offset, using defaults: %s"
658 python-indent-offset
)))))))
660 (defun python-indent-context ()
661 "Get information on indentation context.
662 Context information is returned with a cons with the form:
665 Where status can be any of the following symbols:
666 * inside-paren: If point in between (), {} or []
667 * inside-string: If point is inside a string
668 * after-backslash: Previous line ends in a backslash
669 * after-beginning-of-block: Point is after beginning of block
670 * after-line: Point is after normal line
671 * no-indent: Point is at beginning of buffer or other special case
672 START is the buffer position where the sexp starts."
675 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
679 ;; Beginning of buffer
681 (goto-char (line-beginning-position))
685 ((setq start
(python-syntax-context 'paren ppss
))
688 ((setq start
(python-syntax-context 'string ppss
))
691 ((setq start
(when (not (or (python-syntax-context 'string ppss
)
692 (python-syntax-context 'comment ppss
)))
693 (let ((line-beg-pos (line-beginning-position)))
694 (when (python-info-line-ends-backslash-p
696 (- line-beg-pos
2)))))
698 ;; After beginning of block
699 ((setq start
(save-excursion
701 (back-to-indentation)
702 (python-util-forward-comment -
1)
703 (equal (char-before) ?
:))
704 ;; Move to the first block start that's not in within
705 ;; a string, comment or paren and that's not a
706 ;; continuation line.
707 (while (and (re-search-backward
708 (python-rx block-start
) nil t
)
710 (python-syntax-context-type)
711 (python-info-continuation-line-p))))
712 (when (looking-at (python-rx block-start
))
714 'after-beginning-of-block
)
716 ((setq start
(save-excursion
717 (back-to-indentation)
718 (python-util-forward-comment -
1)
719 (python-nav-beginning-of-statement)
726 (defun python-indent-calculate-indentation ()
727 "Calculate correct indentation offset for the current line."
728 (let* ((indentation-context (python-indent-context))
729 (context-status (car indentation-context
))
730 (context-start (cdr indentation-context
)))
736 ;; When point is after beginning of block just add one level
737 ;; of indentation relative to the context-start
738 ('after-beginning-of-block
739 (goto-char context-start
)
740 (+ (current-indentation) python-indent-offset
))
741 ;; When after a simple line just use previous line
742 ;; indentation, in the case current line starts with a
743 ;; `python-indent-dedenters' de-indent one level.
747 (goto-char context-start
)
748 (current-indentation))
750 (back-to-indentation)
751 (looking-at (regexp-opt python-indent-dedenters
)))
754 ;; When inside of a string, do nothing. just use the current
755 ;; indentation. XXX: perhaps it would be a good idea to
756 ;; invoke standard text indentation here
758 (goto-char context-start
)
759 (current-indentation))
760 ;; After backslash we have several possibilities.
763 ;; Check if current line is a dot continuation. For this
764 ;; the current line must start with a dot and previous
765 ;; line must contain a dot too.
767 (back-to-indentation)
768 (when (looking-at "\\.")
769 ;; If after moving one line back point is inside a paren it
770 ;; needs to move back until it's not anymore
774 (python-syntax-context 'paren
))))
775 (goto-char (line-end-position))
776 (while (and (re-search-backward
777 "\\." (line-beginning-position) t
)
778 (python-syntax-context-type)))
779 (if (and (looking-at "\\.")
780 (not (python-syntax-context-type)))
781 ;; The indentation is the same column of the
782 ;; first matching dot that's not inside a
783 ;; comment, a string or a paren
785 ;; No dot found on previous line, just add another
786 ;; indentation level.
787 (+ (current-indentation) python-indent-offset
)))))
788 ;; Check if prev line is a block continuation
789 ((let ((block-continuation-start
790 (python-info-block-continuation-line-p)))
791 (when block-continuation-start
792 ;; If block-continuation-start is set jump to that
793 ;; marker and use first column after the block start
794 ;; as indentation value.
795 (goto-char block-continuation-start
)
797 (python-rx block-start
(* space
))
798 (line-end-position) t
)
800 ;; Check if current line is an assignment continuation
801 ((let ((assignment-continuation-start
802 (python-info-assignment-continuation-line-p)))
803 (when assignment-continuation-start
804 ;; If assignment-continuation is set jump to that
805 ;; marker and use first column after the assignment
806 ;; operator as indentation value.
807 (goto-char assignment-continuation-start
)
811 (goto-char (python-info-beginning-of-backslash))
816 (or (python-info-beginning-of-backslash) (point)))
817 (python-info-line-ends-backslash-p)))
818 ;; The two previous lines ended in a backslash so we must
819 ;; respect previous line indentation.
820 (current-indentation)
821 ;; What happens here is that we are dealing with the second
822 ;; line of a backslash continuation, in that case we just going
823 ;; to add one indentation level.
824 (+ (current-indentation) python-indent-offset
)))))
825 ;; When inside a paren there's a need to handle nesting
829 ;; If current line closes the outermost open paren use the
830 ;; current indentation of the context-start line.
832 (skip-syntax-forward "\s" (line-end-position))
833 (when (and (looking-at (regexp-opt '(")" "]" "}")))
836 (not (python-syntax-context 'paren
))))
837 (goto-char context-start
)
838 (current-indentation))))
839 ;; If open paren is contained on a line by itself add another
840 ;; indentation level, else look for the first word after the
841 ;; opening paren and use it's column position as indentation
843 ((let* ((content-starts-in-newline)
846 (if (setq content-starts-in-newline
848 (goto-char context-start
)
852 (line-beginning-position)
854 (python-util-forward-comment))
856 (+ (current-indentation) python-indent-offset
)
860 ;; If current line closes a nested open paren de-indent one
863 (back-to-indentation)
864 (looking-at (regexp-opt '(")" "]" "}"))))
865 (- indent python-indent-offset
))
866 ;; If the line of the opening paren that wraps the current
867 ;; line starts a block add another level of indentation to
868 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
870 (when (and content-starts-in-newline
872 (goto-char context-start
)
873 (back-to-indentation)
874 (looking-at (python-rx block-start
))))
875 (+ indent python-indent-offset
))))
878 (defun python-indent-calculate-levels ()
879 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
880 (let* ((indentation (python-indent-calculate-indentation))
881 (remainder (% indentation python-indent-offset
))
882 (steps (/ (- indentation remainder
) python-indent-offset
)))
883 (setq python-indent-levels
(list 0))
884 (dotimes (step steps
)
885 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
886 (when (not (eq 0 remainder
))
887 (push (+ (* python-indent-offset steps
) remainder
) python-indent-levels
))
888 (setq python-indent-levels
(nreverse python-indent-levels
))
889 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
891 (defun python-indent-toggle-levels ()
892 "Toggle `python-indent-current-level' over `python-indent-levels'."
893 (setq python-indent-current-level
(1- python-indent-current-level
))
894 (when (< python-indent-current-level
0)
895 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
897 (defun python-indent-line (&optional force-toggle
)
898 "Internal implementation of `python-indent-line-function'.
899 Uses the offset calculated in
900 `python-indent-calculate-indentation' and available levels
901 indicated by the variable `python-indent-levels' to set the
904 When the variable `last-command' is equal to
905 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
906 levels indicated in the variable `python-indent-levels' by
907 setting the current level in the variable
908 `python-indent-current-level'.
910 When the variable `last-command' is not equal to
911 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
912 possible indentation levels and saves it in the variable
913 `python-indent-levels'. Afterwards it sets the variable
914 `python-indent-current-level' correctly so offset is equal
915 to (`nth' `python-indent-current-level' `python-indent-levels')"
917 (and (or (and (eq this-command
'indent-for-tab-command
)
918 (eq last-command this-command
))
920 (not (equal python-indent-levels
'(0)))
921 (or (python-indent-toggle-levels) t
))
922 (python-indent-calculate-levels))
923 (let* ((starting-pos (point-marker))
924 (indent-ending-position
925 (+ (line-beginning-position) (current-indentation)))
926 (follow-indentation-p
928 (and (<= (line-beginning-position) starting-pos
)
929 (>= indent-ending-position starting-pos
))))
930 (next-indent (nth python-indent-current-level python-indent-levels
)))
931 (unless (= next-indent
(current-indentation))
933 (delete-horizontal-space)
934 (indent-to next-indent
)
935 (goto-char starting-pos
))
936 (and follow-indentation-p
(back-to-indentation)))
937 (python-info-closing-block-message))
939 (defun python-indent-line-function ()
940 "`indent-line-function' for Python mode.
941 See `python-indent-line' for details."
942 (python-indent-line))
944 (defun python-indent-dedent-line ()
945 "De-indent current line."
947 (when (and (not (python-syntax-comment-or-string-p))
948 (<= (point-marker) (save-excursion
949 (back-to-indentation)
951 (> (current-column) 0))
952 (python-indent-line t
)
955 (defun python-indent-dedent-line-backspace (arg)
956 "De-indent current line.
957 Argument ARG is passed to `backward-delete-char-untabify' when
958 point is not in between the indentation."
960 (when (not (python-indent-dedent-line))
961 (backward-delete-char-untabify arg
)))
962 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
964 (defun python-indent-region (start end
)
965 "Indent a python region automagically.
967 Called from a program, START and END specify the region to indent."
968 (let ((deactivate-mark nil
))
971 (setq end
(point-marker))
973 (or (bolp) (forward-line 1))
974 (while (< (point) end
)
975 (or (and (bolp) (eolp))
978 (back-to-indentation)
979 (setq word
(current-word))
983 (delete-horizontal-space)
984 (indent-to (python-indent-calculate-indentation)))))
986 (move-marker end nil
))))
988 (defun python-indent-shift-left (start end
&optional count
)
989 "Shift lines contained in region START END by COUNT columns to the left.
990 COUNT defaults to `python-indent-offset'. If region isn't
991 active, the current line is shifted. The shifted region includes
992 the lines in which START and END lie. An error is signaled if
993 any lines in the region are indented less than COUNT columns."
996 (list (region-beginning) (region-end) current-prefix-arg
)
997 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
999 (setq count
(prefix-numeric-value count
))
1000 (setq count python-indent-offset
))
1002 (let ((deactivate-mark nil
))
1005 (while (< (point) end
)
1006 (if (and (< (current-indentation) count
)
1007 (not (looking-at "[ \t]*$")))
1008 (error "Can't shift all lines enough"))
1010 (indent-rigidly start end
(- count
))))))
1012 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
1014 (defun python-indent-shift-right (start end
&optional count
)
1015 "Shift lines contained in region START END by COUNT columns to the left.
1016 COUNT defaults to `python-indent-offset'. If region isn't
1017 active, the current line is shifted. The shifted region includes
1018 the lines in which START and END lie."
1021 (list (region-beginning) (region-end) current-prefix-arg
)
1022 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1023 (let ((deactivate-mark nil
))
1025 (setq count
(prefix-numeric-value count
))
1026 (setq count python-indent-offset
))
1027 (indent-rigidly start end count
)))
1029 (defun python-indent-electric-colon (arg)
1030 "Insert a colon and maybe de-indent the current line.
1031 With numeric ARG, just insert that many colons. With
1032 \\[universal-argument], just insert a single colon."
1034 (self-insert-command (if (not (integerp arg
)) 1 arg
))
1035 (when (and (not arg
)
1037 (not (equal ?
: (char-after (- (point-marker) 2))))
1038 (not (python-syntax-comment-or-string-p)))
1039 (let ((indentation (current-indentation))
1040 (calculated-indentation (python-indent-calculate-indentation)))
1041 (python-info-closing-block-message)
1042 (when (> indentation calculated-indentation
)
1044 (indent-line-to calculated-indentation
)
1045 (when (not (python-info-closing-block-message))
1046 (indent-line-to indentation
)))))))
1047 (put 'python-indent-electric-colon
'delete-selection t
)
1049 (defun python-indent-post-self-insert-function ()
1050 "Adjust closing paren line indentation after a char is added.
1051 This function is intended to be added to the
1052 `post-self-insert-hook.' If a line renders a paren alone, after
1053 adding a char before it, the line will be re-indented
1054 automatically if needed."
1055 (when (and (eq (char-before) last-command-event
)
1057 (memq (char-after) '(?\
) ?\
] ?\
})))
1059 (goto-char (line-beginning-position))
1060 ;; If after going to the beginning of line the point
1061 ;; is still inside a paren it's ok to do the trick
1062 (when (python-syntax-context 'paren
)
1063 (let ((indentation (python-indent-calculate-indentation)))
1064 (when (< (current-indentation) indentation
)
1065 (indent-line-to indentation
)))))))
1070 (defvar python-nav-beginning-of-defun-regexp
1071 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1072 "Regexp matching class or function definition.
1073 The name of the defun should be grouped so it can be retrieved
1074 via `match-string'.")
1076 (defun python-nav-beginning-of-defun (&optional arg
)
1077 "Move point to `beginning-of-defun'.
1078 With positive ARG move search backwards. With negative do the
1079 same but forward. When ARG is nil or 0 defaults to 1. This is
1080 the main part of `python-beginning-of-defun-function'. Return
1081 non-nil if point is moved to `beginning-of-defun'."
1082 (when (or (null arg
) (= arg
0)) (setq arg
1))
1083 (let* ((re-search-fn (if (> arg
0)
1084 #'re-search-backward
1085 #'re-search-forward
))
1086 (line-beg-pos (line-beginning-position))
1087 (line-content-start (+ line-beg-pos
(current-indentation)))
1088 (pos (point-marker))
1091 (when (and (< arg
0)
1092 (python-info-looking-at-beginning-of-defun))
1094 (while (and (funcall re-search-fn
1095 python-nav-beginning-of-defun-regexp nil t
)
1096 (python-syntax-context-type)))
1097 (and (python-info-looking-at-beginning-of-defun)
1098 (or (not (= (line-number-at-pos pos
)
1099 (line-number-at-pos)))
1100 (and (>= (point) line-beg-pos
)
1101 (<= (point) line-content-start
)
1102 (> pos line-content-start
)))))))
1104 (or (beginning-of-line 1) t
)
1105 (and (goto-char pos
) nil
))))
1107 (defun python-beginning-of-defun-function (&optional arg
)
1108 "Move point to the beginning of def or class.
1109 With positive ARG move that number of functions backwards. With
1110 negative do the same but forward. When ARG is nil or 0 defaults
1111 to 1. Return non-nil if point is moved to `beginning-of-defun'."
1112 (when (or (null arg
) (= arg
0)) (setq arg
1))
1114 (cond ((and (eq this-command
'mark-defun
)
1115 (python-info-looking-at-beginning-of-defun)))
1117 (dotimes (i (if (> arg
0) arg
(- arg
)))
1118 (when (and (python-nav-beginning-of-defun arg)
1123 (defun python-end-of-defun-function ()
1124 "Move point to the end of def or class.
1125 Returns nil if point is not in a def or class."
1127 (let ((beg-defun-indent))
1128 (when (or (python-info-looking-at-beginning-of-defun)
1129 (python-beginning-of-defun-function 1)
1130 (python-beginning-of-defun-function -
1))
1131 (setq beg-defun-indent
(current-indentation))
1133 ;; Go as forward as possible
1135 (python-nav-beginning-of-defun -1)
1136 (and (goto-char (point-max)) nil
))
1137 (> (current-indentation) beg-defun-indent
)))
1138 (beginning-of-line 1)
1139 ;; Go as backwards as possible
1140 (while (and (forward-line -
1)
1142 (or (not (current-word))
1143 (equal (char-after (+ (point) (current-indentation))) ?
#)
1144 (<= (current-indentation) beg-defun-indent
)
1145 (looking-at (python-rx decorator
))
1146 (python-syntax-context-type))))
1148 ;; If point falls inside a paren or string context the point is
1149 ;; forwarded at the end of it (or end of buffer if its not closed)
1150 (let ((context-type (python-syntax-context-type)))
1151 (when (memq context-type
'(paren string
))
1153 (while (and (not (eobp))
1154 (python-syntax-context-type))
1155 (forward-line 1)))))))
1157 (defun python-nav-beginning-of-statement ()
1158 "Move to start of current statement."
1160 (while (and (or (back-to-indentation) t
)
1165 (python-info-line-ends-backslash-p))
1166 (python-syntax-context 'string
)
1167 (python-syntax-context 'paren
))
1168 (forward-line -
1)))))
1170 (defun python-nav-end-of-statement ()
1171 "Move to end of current statement."
1173 (while (and (goto-char (line-end-position))
1176 (python-info-line-ends-backslash-p)
1177 (python-syntax-context 'string
)
1178 (python-syntax-context 'paren
))
1179 (forward-line 1)))))
1181 (defun python-nav-backward-statement (&optional arg
)
1182 "Move backward to previous statement.
1183 With ARG, repeat. See `python-nav-forward-statement'."
1185 (or arg
(setq arg
1))
1186 (python-nav-forward-statement (- arg
)))
1188 (defun python-nav-forward-statement (&optional arg
)
1189 "Move forward to next statement.
1190 With ARG, repeat. With negative argument, move ARG times
1191 backward to previous statement."
1193 (or arg
(setq arg
1))
1195 (python-nav-end-of-statement)
1196 (python-util-forward-comment)
1197 (python-nav-beginning-of-statement)
1198 (setq arg
(1- arg
)))
1200 (python-nav-beginning-of-statement)
1201 (python-util-forward-comment -
1)
1202 (python-nav-beginning-of-statement)
1203 (setq arg
(1+ arg
))))
1205 (defun python-nav-beginning-of-block ()
1206 "Move to start of current block."
1208 (let ((starting-pos (point))
1209 (block-regexp (python-rx
1210 line-start
(* whitespace
) block-start
)))
1212 (python-nav-beginning-of-statement)
1213 (looking-at (python-rx block-start
)))
1215 ;; Go to first line beginning a statement
1216 (while (and (not (bobp))
1217 (or (and (python-nav-beginning-of-statement) nil
)
1218 (python-info-current-line-comment-p)
1219 (python-info-current-line-empty-p)))
1221 (let ((block-matching-indent
1222 (- (current-indentation) python-indent-offset
)))
1224 (and (python-nav-backward-block)
1225 (> (current-indentation) block-matching-indent
)))
1226 (if (and (looking-at (python-rx block-start
))
1227 (= (current-indentation) block-matching-indent
))
1229 (and (goto-char starting-pos
) nil
))))))
1231 (defun python-nav-end-of-block ()
1232 "Move to end of current block."
1234 (when (python-nav-beginning-of-block)
1235 (let ((block-indentation (current-indentation)))
1236 (python-nav-end-of-statement)
1237 (while (and (forward-line 1)
1239 (or (and (> (current-indentation) block-indentation
)
1240 (or (python-nav-end-of-statement) t
))
1241 (python-info-current-line-comment-p)
1242 (python-info-current-line-empty-p))))
1243 (python-util-forward-comment -
1)
1246 (defun python-nav-backward-block (&optional arg
)
1247 "Move backward to previous block of code.
1248 With ARG, repeat. See `python-nav-forward-block'."
1250 (or arg
(setq arg
1))
1251 (python-nav-forward-block (- arg
)))
1253 (defun python-nav-forward-block (&optional arg
)
1254 "Move forward to next block of code.
1255 With ARG, repeat. With negative argument, move ARG times
1256 backward to previous block."
1258 (or arg
(setq arg
1))
1259 (let ((block-start-regexp
1260 (python-rx line-start
(* whitespace
) block-start
))
1261 (starting-pos (point)))
1263 (python-nav-end-of-statement)
1265 (re-search-forward block-start-regexp nil t
)
1266 (python-syntax-context-type)))
1267 (setq arg
(1- arg
)))
1269 (python-nav-beginning-of-statement)
1271 (re-search-backward block-start-regexp nil t
)
1272 (python-syntax-context-type)))
1273 (setq arg
(1+ arg
)))
1274 (python-nav-beginning-of-statement)
1275 (if (not (looking-at (python-rx block-start
)))
1276 (and (goto-char starting-pos
) nil
)
1277 (and (not (= (point) starting-pos
)) (point-marker)))))
1279 (defun python-nav-lisp-forward-sexp-safe (&optional arg
)
1280 "Safe version of standard `forward-sexp'.
1281 When ARG > 0 move forward, else if ARG is < 0."
1282 (or arg
(setq arg
1))
1283 (let ((forward-sexp-function nil
)
1285 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1287 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1291 (while (and (funcall search-fn paren-regexp nil t
)
1292 (python-syntax-context 'paren
)))))))
1294 (defun python-nav--forward-sexp ()
1295 "Move to forward sexp."
1296 (case (python-syntax-context-type)
1298 ;; Inside of a string, get out of it.
1299 (while (and (re-search-forward "[\"']" nil t
)
1300 (python-syntax-context 'string
))))
1302 ;; Inside of a comment, just move forward.
1303 (python-util-forward-comment))
1305 (python-nav-lisp-forward-sexp-safe 1))
1307 (if (and (not (eobp))
1308 (= (syntax-class (syntax-after (point))) 4))
1309 ;; Looking an open-paren
1310 (python-nav-lisp-forward-sexp-safe 1)
1311 (let ((block-starting-pos
1312 (save-excursion (python-nav-beginning-of-block)))
1314 (save-excursion (python-nav-end-of-block)))
1315 (next-block-starting-pos
1316 (save-excursion (python-nav-forward-block))))
1318 ((not block-starting-pos
)
1319 ;; Not inside a block, move to closest one.
1320 (and next-block-starting-pos
1321 (goto-char next-block-starting-pos
)))
1322 ((= (point) block-starting-pos
)
1323 ;; Point is at beginning of block
1324 (if (and next-block-starting-pos
1325 (< next-block-starting-pos block-ending-pos
))
1326 ;; Beginning of next block is closer than current's
1328 (goto-char next-block-starting-pos
)
1329 (goto-char block-ending-pos
)))
1330 ((= block-ending-pos
(point))
1331 ;; Point is at end of current block
1332 (let ((parent-block-end-pos
1334 (python-util-forward-comment)
1335 (python-nav-beginning-of-block)
1336 (python-nav-end-of-block))))
1337 (if (and parent-block-end-pos
1338 (or (not next-block-starting-pos
)
1339 (> next-block-starting-pos parent-block-end-pos
)))
1340 ;; If the parent block ends before next block
1341 ;; starts move to it.
1342 (goto-char parent-block-end-pos
)
1343 (and next-block-starting-pos
1344 (goto-char next-block-starting-pos
)))))
1345 (t (python-nav-end-of-block))))))))
1347 (defun python-nav--backward-sexp ()
1348 "Move to backward sexp."
1349 (case (python-syntax-context-type)
1351 ;; Inside of a string, get out of it.
1352 (while (and (re-search-backward "[\"']" nil t
)
1353 (python-syntax-context 'string
))))
1355 ;; Inside of a comment, just move backward.
1356 (python-util-forward-comment -
1))
1358 ;; Handle parens like we are lisp.
1359 (python-nav-lisp-forward-sexp-safe -
1))
1361 (let* ((block-starting-pos
1362 (save-excursion (python-nav-beginning-of-block)))
1364 (save-excursion (python-nav-end-of-block)))
1365 (prev-block-ending-pos
1366 (save-excursion (when (python-nav-backward-block)
1367 (python-nav-end-of-block))))
1368 (prev-block-parent-ending-pos
1370 (when prev-block-ending-pos
1371 (goto-char prev-block-ending-pos
)
1372 (python-util-forward-comment)
1373 (python-nav-beginning-of-block)
1374 (python-nav-end-of-block)))))
1375 (if (and (not (bobp))
1376 (= (syntax-class (syntax-after (1- (point)))) 5))
1377 ;; Char before point is a paren closing char, handle it
1378 ;; like we are lisp.
1379 (python-nav-lisp-forward-sexp-safe -
1)
1381 ((not block-ending-pos
)
1382 ;; Not in and ending pos, move to end of previous block.
1383 (and (python-nav-backward-block)
1384 (python-nav-end-of-block)))
1385 ((= (point) block-ending-pos
)
1386 ;; In ending pos, we need to search backwards for the
1387 ;; closest point looking the list of candidates from here.
1390 '(prev-block-parent-ending-pos
1391 prev-block-ending-pos
1393 block-starting-pos
))
1394 (when (and (symbol-value name
)
1395 (< (symbol-value name
) (point)))
1396 (add-to-list 'candidates
(symbol-value name
))))
1397 (goto-char (apply 'max candidates
))))
1398 ((> (point) block-ending-pos
)
1399 ;; After an ending position, move to it.
1400 (goto-char block-ending-pos
))
1401 ((= (point) block-starting-pos
)
1402 ;; On a block starting position.
1403 (if (not (> (point) (or prev-block-ending-pos
(point))))
1404 ;; Point is after the end position of the block that
1405 ;; wraps the current one, just move a block backward.
1406 (python-nav-backward-block)
1407 ;; If we got here we are facing a case like this one:
1411 ;; except Exception as e:
1413 ;; Where point is on the "except" and must move to the
1415 (goto-char prev-block-ending-pos
)
1416 (let ((parent-block-ending-pos
1418 (python-nav-forward-sexp)
1419 (and (not (looking-at (python-rx block-start
)))
1421 (when (and parent-block-ending-pos
1422 (> parent-block-ending-pos prev-block-ending-pos
))
1423 ;; If we got here we are facing a case like this one:
1425 ;; except ImportError:
1429 ;; except AttributeError:
1431 ;; Where point is on the "except" and must move to
1432 ;; the end of "here()". Without this extra step we'd
1433 ;; just get to the end of processing().
1434 (goto-char parent-block-ending-pos
)))))
1436 (if (and prev-block-ending-pos
(< prev-block-ending-pos
(point)))
1437 (goto-char prev-block-ending-pos
)
1438 (python-nav-beginning-of-block)))))))))
1440 (defun python-nav-forward-sexp (&optional arg
)
1441 "Move forward across one block of code.
1442 With ARG, do it that many times. Negative arg -N means
1443 move backward N times."
1445 (or arg
(setq arg
1))
1447 (python-nav--forward-sexp)
1448 (setq arg
(1- arg
)))
1450 (python-nav--backward-sexp)
1451 (setq arg
(1+ arg
))))
1454 ;;; Shell integration
1456 (defcustom python-shell-buffer-name
"Python"
1457 "Default buffer name for Python interpreter."
1462 (defcustom python-shell-interpreter
"python"
1463 "Default Python interpreter for shell."
1467 (defcustom python-shell-internal-buffer-name
"Python Internal"
1468 "Default buffer name for the Internal Python interpreter."
1473 (defcustom python-shell-interpreter-args
"-i"
1474 "Default arguments for the Python interpreter."
1478 (defcustom python-shell-prompt-regexp
">>> "
1479 "Regular Expression matching top\-level input prompt of python shell.
1480 It should not contain a caret (^) at the beginning."
1485 (defcustom python-shell-prompt-block-regexp
"[.][.][.] "
1486 "Regular Expression matching block input prompt of python shell.
1487 It should not contain a caret (^) at the beginning."
1492 (defcustom python-shell-prompt-output-regexp
""
1493 "Regular Expression matching output prompt of python shell.
1494 It should not contain a caret (^) at the beginning."
1499 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1500 "Regular Expression matching pdb input prompt of python shell.
1501 It should not contain a caret (^) at the beginning."
1506 (defcustom python-shell-enable-font-lock t
1507 "Should syntax highlighting be enabled in the python shell buffer?
1508 Restart the python shell after changing this variable for it to take effect."
1513 (defcustom python-shell-process-environment nil
1514 "List of environment variables for Python shell.
1515 This variable follows the same rules as `process-environment'
1516 since it merges with it before the process creation routines are
1517 called. When this variable is nil, the Python shell is run with
1518 the default `process-environment'."
1519 :type
'(repeat string
)
1523 (defcustom python-shell-extra-pythonpaths nil
1524 "List of extra pythonpaths for Python shell.
1525 The values of this variable are added to the existing value of
1526 PYTHONPATH in the `process-environment' variable."
1527 :type
'(repeat string
)
1531 (defcustom python-shell-exec-path nil
1532 "List of path to search for binaries.
1533 This variable follows the same rules as `exec-path' since it
1534 merges with it before the process creation routines are called.
1535 When this variable is nil, the Python shell is run with the
1536 default `exec-path'."
1537 :type
'(repeat string
)
1541 (defcustom python-shell-virtualenv-path nil
1542 "Path to virtualenv root.
1543 This variable, when set to a string, makes the values stored in
1544 `python-shell-process-environment' and `python-shell-exec-path'
1545 to be modified properly so shells are started with the specified
1551 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1552 python-ffap-setup-code
1553 python-eldoc-setup-code
)
1554 "List of code run by `python-shell-send-setup-codes'."
1555 :type
'(repeat symbol
)
1559 (defcustom python-shell-compilation-regexp-alist
1560 `((,(rx line-start
(1+ (any " \t")) "File \""
1561 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1562 "\", line " (group (1+ digit
)))
1564 (,(rx " in file " (group (1+ not-newline
)) " on line "
1567 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1568 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1570 "`compilation-error-regexp-alist' for inferior Python."
1571 :type
'(alist string
)
1574 (defun python-shell-get-process-name (dedicated)
1575 "Calculate the appropriate process name for inferior Python process.
1576 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1577 returns a string with the form
1578 `python-shell-buffer-name'[variable `buffer-file-name'] else
1579 returns the value of `python-shell-buffer-name'."
1583 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
1584 (format "%s" python-shell-buffer-name
))))
1587 (defun python-shell-internal-get-process-name ()
1588 "Calculate the appropriate process name for Internal Python process.
1589 The name is calculated from `python-shell-global-buffer-name' and
1590 a hash of all relevant global shell settings in order to ensure
1591 uniqueness for different types of configurations."
1593 python-shell-internal-buffer-name
1596 (python-shell-parse-command)
1597 python-shell-prompt-regexp
1598 python-shell-prompt-block-regexp
1599 python-shell-prompt-output-regexp
1600 (mapconcat #'symbol-value python-shell-setup-codes
"")
1601 (mapconcat #'identity python-shell-process-environment
"")
1602 (mapconcat #'identity python-shell-extra-pythonpaths
"")
1603 (mapconcat #'identity python-shell-exec-path
"")
1604 (or python-shell-virtualenv-path
"")
1605 (mapconcat #'identity python-shell-exec-path
"")))))
1607 (defun python-shell-parse-command ()
1608 "Calculate the string used to execute the inferior Python process."
1609 (format "%s %s" python-shell-interpreter python-shell-interpreter-args
))
1611 (defun python-shell-calculate-process-environment ()
1612 "Calculate process environment given `python-shell-virtualenv-path'."
1613 (let ((process-environment (append
1614 python-shell-process-environment
1615 process-environment nil
))
1616 (virtualenv (if python-shell-virtualenv-path
1617 (directory-file-name python-shell-virtualenv-path
)
1619 (when python-shell-extra-pythonpaths
1620 (setenv "PYTHONPATH"
1622 (mapconcat 'identity
1623 python-shell-extra-pythonpaths
1626 (or (getenv "PYTHONPATH") ""))))
1627 (if (not virtualenv
)
1629 (setenv "PYTHONHOME" nil
)
1630 (setenv "PATH" (format "%s/bin%s%s"
1631 virtualenv path-separator
1632 (or (getenv "PATH") "")))
1633 (setenv "VIRTUAL_ENV" virtualenv
))
1634 process-environment
))
1636 (defun python-shell-calculate-exec-path ()
1637 "Calculate exec path given `python-shell-virtualenv-path'."
1638 (let ((path (append python-shell-exec-path
1640 (if (not python-shell-virtualenv-path
)
1642 (cons (format "%s/bin"
1643 (directory-file-name python-shell-virtualenv-path
))
1646 (defun python-comint-output-filter-function (output)
1647 "Hook run after content is put into comint buffer.
1648 OUTPUT is a string with the contents of the buffer."
1649 (ansi-color-filter-apply output
))
1651 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1652 "Major mode for Python inferior process.
1653 Runs a Python interpreter as a subprocess of Emacs, with Python
1654 I/O through an Emacs buffer. Variables
1655 `python-shell-interpreter' and `python-shell-interpreter-args'
1656 controls which Python interpreter is run. Variables
1657 `python-shell-prompt-regexp',
1658 `python-shell-prompt-output-regexp',
1659 `python-shell-prompt-block-regexp',
1660 `python-shell-enable-font-lock',
1661 `python-shell-completion-setup-code',
1662 `python-shell-completion-string-code',
1663 `python-shell-completion-module-string-code',
1664 `python-eldoc-setup-code', `python-eldoc-string-code',
1665 `python-ffap-setup-code' and `python-ffap-string-code' can
1666 customize this mode for different Python interpreters.
1668 You can also add additional setup code to be run at
1669 initialization of the interpreter via `python-shell-setup-codes'
1672 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1673 (set-syntax-table python-mode-syntax-table
)
1674 (setq mode-line-process
'(":%s"))
1675 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1676 python-shell-prompt-regexp
1677 python-shell-prompt-block-regexp
1678 python-shell-prompt-pdb-regexp
))
1679 (make-local-variable 'comint-output-filter-functions
)
1680 (add-hook 'comint-output-filter-functions
1681 'python-comint-output-filter-function
)
1682 (add-hook 'comint-output-filter-functions
1683 'python-pdbtrack-comint-output-filter-function
)
1684 (set (make-local-variable 'compilation-error-regexp-alist
)
1685 python-shell-compilation-regexp-alist
)
1686 (define-key inferior-python-mode-map
[remap complete-symbol
]
1687 'completion-at-point
)
1688 (add-hook 'completion-at-point-functions
1689 'python-shell-completion-complete-at-point nil
'local
)
1690 (add-to-list (make-local-variable 'comint-dynamic-complete-functions
)
1691 'python-shell-completion-complete-at-point
)
1692 (define-key inferior-python-mode-map
"\t"
1693 'python-shell-completion-complete-or-indent
)
1694 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
1695 (make-local-variable 'python-pdbtrack-tracked-buffer
)
1696 (make-local-variable 'python-shell-internal-last-output
)
1697 (when python-shell-enable-font-lock
1698 (set (make-local-variable 'font-lock-defaults
)
1699 '(python-font-lock-keywords nil nil nil nil
))
1700 (set (make-local-variable 'syntax-propertize-function
)
1701 python-syntax-propertize-function
))
1702 (compilation-shell-minor-mode 1))
1704 (defun python-shell-make-comint (cmd proc-name
&optional pop internal
)
1705 "Create a python shell comint buffer.
1706 CMD is the python command to be executed and PROC-NAME is the
1707 process name the comint buffer will get. After the comint buffer
1708 is created the `inferior-python-mode' is activated. When
1709 optional argument POP is non-nil the buffer is shown. When
1710 optional argument INTERNAL is non-nil this process is run on a
1711 buffer with a name that starts with a space, following the Emacs
1712 convention for temporary/internal buffers, and also makes sure
1713 the user is not queried for confirmation when the process is
1716 (let* ((proc-buffer-name
1717 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
1718 (process-environment (python-shell-calculate-process-environment))
1719 (exec-path (python-shell-calculate-exec-path)))
1720 (when (not (comint-check-proc proc-buffer-name
))
1721 (let* ((cmdlist (split-string-and-unquote cmd
))
1722 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1723 (car cmdlist
) nil
(cdr cmdlist
)))
1724 (current-buffer (current-buffer))
1725 (process (get-buffer-process buffer
)))
1726 (with-current-buffer buffer
1727 (inferior-python-mode)
1728 (python-util-clone-local-variables current-buffer
))
1729 (accept-process-output process
)
1730 (and pop
(pop-to-buffer buffer t
))
1731 (and internal
(set-process-query-on-exit-flag process nil
))))
1735 (defun run-python (cmd &optional dedicated show
)
1736 "Run an inferior Python process.
1737 Input and output via buffer named after
1738 `python-shell-buffer-name'. If there is a process already
1739 running in that buffer, just switch to it.
1741 With argument, allows you to define CMD so you can edit the
1742 command used to call the interpreter and define DEDICATED, so a
1743 dedicated process for the current buffer is open. When numeric
1744 prefix arg is other than 0 or 4 do not SHOW.
1746 Runs the hook `inferior-python-mode-hook' (after the
1747 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1748 process buffer for a list of commands.)"
1750 (if current-prefix-arg
1752 (read-string "Run Python: " (python-shell-parse-command))
1753 (y-or-n-p "Make dedicated process? ")
1754 (= (prefix-numeric-value current-prefix-arg
) 4))
1755 (list (python-shell-parse-command) nil t
)))
1756 (python-shell-make-comint
1757 cmd
(python-shell-get-process-name dedicated
) show
)
1760 (defun run-python-internal ()
1761 "Run an inferior Internal Python process.
1762 Input and output via buffer named after
1763 `python-shell-internal-buffer-name' and what
1764 `python-shell-internal-get-process-name' returns.
1766 This new kind of shell is intended to be used for generic
1767 communication related to defined configurations, the main
1768 difference with global or dedicated shells is that these ones are
1769 attached to a configuration, not a buffer. This means that can
1770 be used for example to retrieve the sys.path and other stuff,
1771 without messing with user shells. Note that
1772 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
1773 are set to nil for these shells, so setup codes are not sent at
1775 (let ((python-shell-enable-font-lock nil
)
1776 (inferior-python-mode-hook nil
))
1778 (python-shell-make-comint
1779 (python-shell-parse-command)
1780 (python-shell-internal-get-process-name) nil t
))))
1782 (defun python-shell-get-process ()
1783 "Get inferior Python process for current buffer and return it."
1784 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1785 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1786 (global-proc-name (python-shell-get-process-name nil
))
1787 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1788 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1789 (global-running (comint-check-proc global-proc-buffer-name
)))
1790 ;; Always prefer dedicated
1791 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name
)
1792 (and global-running global-proc-buffer-name
)))))
1794 (defun python-shell-get-or-create-process ()
1795 "Get or create an inferior Python process for current buffer and return it."
1796 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1797 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1798 (global-proc-name (python-shell-get-process-name nil
))
1799 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1800 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1801 (global-running (comint-check-proc global-proc-buffer-name
))
1802 (current-prefix-arg 16))
1803 (when (and (not dedicated-running
) (not global-running
))
1804 (if (call-interactively 'run-python
)
1805 (setq dedicated-running t
)
1806 (setq global-running t
)))
1807 ;; Always prefer dedicated
1808 (get-buffer-process (if dedicated-running
1809 dedicated-proc-buffer-name
1810 global-proc-buffer-name
))))
1812 (defvar python-shell-internal-buffer nil
1813 "Current internal shell buffer for the current buffer.
1814 This is really not necessary at all for the code to work but it's
1815 there for compatibility with CEDET.")
1817 (defvar python-shell-internal-last-output nil
1818 "Last output captured by the internal shell.
1819 This is really not necessary at all for the code to work but it's
1820 there for compatibility with CEDET.")
1822 (defun python-shell-internal-get-or-create-process ()
1823 "Get or create an inferior Internal Python process."
1824 (let* ((proc-name (python-shell-internal-get-process-name))
1825 (proc-buffer-name (format " *%s*" proc-name
)))
1826 (when (not (process-live-p proc-name
))
1827 (run-python-internal)
1828 (setq python-shell-internal-buffer proc-buffer-name
)
1829 ;; XXX: Why is this `sit-for' needed?
1830 ;; `python-shell-make-comint' calls `accept-process-output'
1831 ;; already but it is not helping to get proper output on
1832 ;; 'gnu/linux when the internal shell process is not running and
1833 ;; a call to `python-shell-internal-send-string' is issued.
1835 (get-buffer-process proc-buffer-name
)))
1837 (define-obsolete-function-alias
1838 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
1840 (define-obsolete-variable-alias
1841 'python-buffer
'python-shell-internal-buffer
"24.3")
1843 (define-obsolete-variable-alias
1844 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
1846 (defun python-shell-send-string (string &optional process msg
)
1847 "Send STRING to inferior Python PROCESS.
1848 When MSG is non-nil messages the first line of STRING."
1849 (interactive "sPython command: ")
1850 (let ((process (or process
(python-shell-get-or-create-process)))
1851 (lines (split-string string
"\n" t
)))
1852 (and msg
(message "Sent: %s..." (nth 0 lines
)))
1853 (if (> (length lines
) 1)
1854 (let* ((temporary-file-directory
1855 (if (file-remote-p default-directory
)
1856 (concat (file-remote-p default-directory
) "/tmp")
1857 temporary-file-directory
))
1858 (temp-file-name (make-temp-file "py"))
1859 (file-name (or (buffer-file-name) temp-file-name
)))
1860 (with-temp-file temp-file-name
1862 (delete-trailing-whitespace))
1863 (python-shell-send-file file-name process temp-file-name
))
1864 (comint-send-string process string
)
1865 (when (or (not (string-match "\n$" string
))
1866 (string-match "\n[ \t].*\n?$" string
))
1867 (comint-send-string process
"\n")))))
1869 (defun python-shell-send-string-no-output (string &optional process msg
)
1870 "Send STRING to PROCESS and inhibit output.
1871 When MSG is non-nil messages the first line of STRING. Return
1873 (let* ((output-buffer "")
1874 (process (or process
(python-shell-get-or-create-process)))
1875 (comint-preoutput-filter-functions
1876 (append comint-preoutput-filter-functions
1877 '(ansi-color-filter-apply
1879 (setq output-buffer
(concat output-buffer string
))
1884 (python-shell-send-string string process msg
)
1885 (accept-process-output process
)
1886 (replace-regexp-in-string
1887 (if (> (length python-shell-prompt-output-regexp
) 0)
1888 (format "\n*%s$\\|^%s\\|\n$"
1889 python-shell-prompt-regexp
1890 (or python-shell-prompt-output-regexp
""))
1891 (format "\n*$\\|^%s\\|\n$"
1892 python-shell-prompt-regexp
))
1894 (with-current-buffer (process-buffer process
)
1895 (comint-interrupt-subjob)))))
1897 (defun python-shell-internal-send-string (string)
1898 "Send STRING to the Internal Python interpreter.
1899 Returns the output. See `python-shell-send-string-no-output'."
1900 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
1901 ;; updated to support this new mode.
1902 (setq python-shell-internal-last-output
1903 (python-shell-send-string-no-output
1904 ;; Makes this function compatible with the old
1905 ;; python-send-receive. (At least for CEDET).
1906 (replace-regexp-in-string "_emacs_out +" "" string
)
1907 (python-shell-internal-get-or-create-process) nil
)))
1909 (define-obsolete-function-alias
1910 'python-send-receive
'python-shell-internal-send-string
"24.3")
1912 (define-obsolete-function-alias
1913 'python-send-string
'python-shell-internal-send-string
"24.3")
1915 (defun python-shell-send-region (start end
)
1916 "Send the region delimited by START and END to inferior Python process."
1918 (python-shell-send-string (buffer-substring start end
) nil t
))
1920 (defun python-shell-send-buffer (&optional arg
)
1921 "Send the entire buffer to inferior Python process.
1922 With prefix ARG allow execution of code inside blocks delimited
1923 by \"if __name__== '__main__':\""
1927 (let ((str (buffer-substring (point-min) (point-max))))
1930 (setq str
(replace-regexp-in-string
1931 (python-rx if-name-main
)
1932 "if __name__ == '__main__ ':" str
)))
1933 (python-shell-send-string str
))))
1935 (defun python-shell-send-defun (arg)
1936 "Send the current defun to inferior Python process.
1937 When argument ARG is non-nil do not include decorators."
1940 (python-shell-send-region
1943 (while (and (or (python-beginning-of-defun-function)
1944 (beginning-of-line 1))
1945 (> (current-indentation) 0)))
1947 (while (and (forward-line -
1)
1948 (looking-at (python-rx decorator
))))
1952 (or (python-end-of-defun-function)
1956 (defun python-shell-send-file (file-name &optional process temp-file-name
)
1957 "Send FILE-NAME to inferior Python PROCESS.
1958 If TEMP-FILE-NAME is passed then that file is used for processing
1959 instead, while internally the shell will continue to use
1961 (interactive "fFile to send: ")
1962 (let* ((process (or process
(python-shell-get-or-create-process)))
1963 (temp-file-name (when temp-file-name
1965 (or (file-remote-p temp-file-name
'localname
)
1967 (file-name (or (when file-name
1969 (or (file-remote-p file-name
'localname
)
1972 (when (not file-name
)
1973 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1974 (python-shell-send-string
1976 (concat "__pyfile = open('''%s''');"
1977 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1979 (or temp-file-name file-name
) file-name
)
1982 (defun python-shell-switch-to-shell ()
1983 "Switch to inferior Python process buffer."
1985 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
1987 (defun python-shell-send-setup-code ()
1988 "Send all setup code for shell.
1989 This function takes the list of setup code to send from the
1990 `python-shell-setup-codes' list."
1991 (let ((process (get-buffer-process (current-buffer))))
1992 (dolist (code python-shell-setup-codes
)
1994 (message "Sent %s" code
)
1995 (python-shell-send-string
1996 (symbol-value code
) process
)))))
1998 (add-hook 'inferior-python-mode-hook
1999 #'python-shell-send-setup-code
)
2002 ;;; Shell completion
2004 (defcustom python-shell-completion-setup-code
2008 def __COMPLETER_all_completions(text): []
2011 readline.set_completer(rlcompleter.Completer().complete)
2012 def __COMPLETER_all_completions(text):
2018 res = readline.get_completer()(text, i)
2021 completions.append(res)
2025 "Code used to setup completion in inferior Python processes."
2029 (defcustom python-shell-completion-string-code
2030 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2031 "Python code used to get a string of completions separated by semicolons."
2035 (defcustom python-shell-completion-module-string-code
""
2036 "Python code used to get completions separated by semicolons for imports.
2038 For IPython v0.11, add the following line to
2039 `python-shell-completion-setup-code':
2041 from IPython.core.completerlib import module_completion
2043 and use the following as the value of this variable:
2045 ';'.join(module_completion('''%s'''))\n"
2049 (defcustom python-shell-completion-pdb-string-code
2050 "';'.join(globals().keys() + locals().keys())"
2051 "Python code used to get completions separated by semicolons for [i]pdb."
2055 (defun python-shell-completion-get-completions (process line input
)
2056 "Do completion at point for PROCESS.
2057 LINE is used to detect the context on how to complete given
2060 ;; Get the last prompt for the inferior process
2061 ;; buffer. This is used for the completion code selection
2063 (with-current-buffer (process-buffer process
)
2064 (buffer-substring-no-properties
2065 (overlay-start comint-last-prompt-overlay
)
2066 (overlay-end comint-last-prompt-overlay
))))
2068 ;; Check whether a prompt matches a pdb string, an import
2069 ;; statement or just the standard prompt and use the
2070 ;; correct python-shell-completion-*-code string
2071 (cond ((and (> (length python-shell-completion-pdb-string-code
) 0)
2073 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
2076 (length python-shell-completion-module-string-code
) 0)
2078 (concat "^" python-shell-prompt-regexp
) prompt
)
2079 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line
))
2082 (concat "^" python-shell-prompt-regexp
) prompt
)
2086 (case completion-context
2087 (pdb python-shell-completion-pdb-string-code
)
2088 (import python-shell-completion-module-string-code
)
2089 (default python-shell-completion-string-code
)
2092 (if (eq completion-context
'import
)
2093 (replace-regexp-in-string "^[ \t]+" "" line
)
2095 (and completion-code
2096 (> (length input
) 0)
2097 (with-current-buffer (process-buffer process
)
2098 (let ((completions (python-shell-send-string-no-output
2099 (format completion-code input
) process
)))
2100 (and (> (length completions
) 2)
2101 (split-string completions
2102 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
2104 (defun python-shell-completion-complete-at-point (&optional process
)
2105 "Perform completion at point in inferior Python.
2106 Optional argument PROCESS forces completions to be retrieved
2107 using that one instead of current buffer's process."
2108 (setq process
(or process
(get-buffer-process (current-buffer))))
2111 (with-syntax-table python-dotty-syntax-table
2112 (let* ((paren-depth (car (syntax-ppss)))
2113 (syntax-string "w_")
2114 (syntax-list (string-to-syntax syntax-string
)))
2115 ;; Stop scanning for the beginning of the completion
2116 ;; subject after the char before point matches a
2119 (car (syntax-after (1- (point)))) syntax-list
)
2120 (skip-syntax-backward syntax-string
)
2121 (when (or (equal (char-before) ?\
))
2122 (equal (char-before) ?
\"))
2125 ;; honor initial paren depth
2126 (> (car (syntax-ppss)) paren-depth
)
2127 (python-syntax-context 'string
))
2132 (completion-table-dynamic
2134 #'python-shell-completion-get-completions
2135 process
(buffer-substring-no-properties
2136 (line-beginning-position) end
))))))
2138 (defun python-shell-completion-complete-or-indent ()
2139 "Complete or indent depending on the context.
2140 If content before pointer is all whitespace indent. If not try
2143 (if (string-match "^[[:space:]]*$"
2144 (buffer-substring (comint-line-beginning-position)
2146 (indent-for-tab-command)
2147 (completion-at-point)))
2150 ;;; PDB Track integration
2152 (defcustom python-pdbtrack-activate t
2153 "Non-nil makes python shell enable pdbtracking."
2158 (defcustom python-pdbtrack-stacktrace-info-regexp
2159 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2160 "Regular Expression matching stacktrace information.
2161 Used to extract the current line and module being inspected."
2166 (defvar python-pdbtrack-tracked-buffer nil
2167 "Variable containing the value of the current tracked buffer.
2168 Never set this variable directly, use
2169 `python-pdbtrack-set-tracked-buffer' instead.")
2171 (defvar python-pdbtrack-buffers-to-kill nil
2172 "List of buffers to be deleted after tracking finishes.")
2174 (defun python-pdbtrack-set-tracked-buffer (file-name)
2175 "Set the buffer for FILE-NAME as the tracked buffer.
2176 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2177 Returns the tracked buffer."
2178 (let ((file-buffer (get-file-buffer file-name
)))
2180 (setq python-pdbtrack-tracked-buffer file-buffer
)
2181 (setq file-buffer
(find-file-noselect file-name
))
2182 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
2183 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
2186 (defun python-pdbtrack-comint-output-filter-function (output)
2187 "Move overlay arrow to current pdb line in tracked buffer.
2188 Argument OUTPUT is a string with the output from the comint process."
2189 (when (and python-pdbtrack-activate
(not (string= output
"")))
2190 (let* ((full-output (ansi-color-filter-apply
2191 (buffer-substring comint-last-input-end
(point-max))))
2195 (insert full-output
)
2196 (goto-char (point-min))
2197 ;; OK, this sucked but now it became a cool hack. The
2198 ;; stacktrace information normally is on the first line
2199 ;; but in some cases (like when doing a step-in) it is
2201 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp
)
2204 (looking-at python-pdbtrack-stacktrace-info-regexp
)))
2205 (setq line-number
(string-to-number
2206 (match-string-no-properties 2)))
2207 (match-string-no-properties 1)))))
2208 (if (and file-name line-number
)
2209 (let* ((tracked-buffer
2210 (python-pdbtrack-set-tracked-buffer file-name
))
2211 (shell-buffer (current-buffer))
2212 (tracked-buffer-window (get-buffer-window tracked-buffer
))
2213 (tracked-buffer-line-pos))
2214 (with-current-buffer tracked-buffer
2215 (set (make-local-variable 'overlay-arrow-string
) "=>")
2216 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
2217 (setq tracked-buffer-line-pos
(progn
2218 (goto-char (point-min))
2219 (forward-line (1- line-number
))
2221 (when tracked-buffer-window
2223 tracked-buffer-window tracked-buffer-line-pos
))
2224 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
2225 (pop-to-buffer tracked-buffer
)
2226 (switch-to-buffer-other-window shell-buffer
))
2227 (when python-pdbtrack-tracked-buffer
2228 (with-current-buffer python-pdbtrack-tracked-buffer
2229 (set-marker overlay-arrow-position nil
))
2230 (mapc #'(lambda (buffer)
2231 (ignore-errors (kill-buffer buffer
)))
2232 python-pdbtrack-buffers-to-kill
)
2233 (setq python-pdbtrack-tracked-buffer nil
2234 python-pdbtrack-buffers-to-kill nil
)))))
2238 ;;; Symbol completion
2240 (defun python-completion-complete-at-point ()
2241 "Complete current symbol at point.
2242 For this to work the best as possible you should call
2243 `python-shell-send-buffer' from time to time so context in
2244 inferior python process is updated properly."
2245 (let ((process (python-shell-get-process)))
2247 (error "Completion needs an inferior Python process running")
2248 (python-shell-completion-complete-at-point process
))))
2250 (add-to-list 'debug-ignored-errors
2251 "^Completion needs an inferior Python process running.")
2256 (defcustom python-fill-comment-function
'python-fill-comment
2257 "Function to fill comments.
2258 This is the function used by `python-fill-paragraph-function' to
2264 (defcustom python-fill-string-function
'python-fill-string
2265 "Function to fill strings.
2266 This is the function used by `python-fill-paragraph-function' to
2272 (defcustom python-fill-decorator-function
'python-fill-decorator
2273 "Function to fill decorators.
2274 This is the function used by `python-fill-paragraph-function' to
2280 (defcustom python-fill-paren-function
'python-fill-paren
2281 "Function to fill parens.
2282 This is the function used by `python-fill-paragraph-function' to
2288 (defun python-fill-paragraph-function (&optional justify
)
2289 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2290 If any of the current line is in or at the end of a multi-line string,
2291 fill the string or the paragraph of it that point is in, preserving
2292 the string's indentation.
2293 Optional argument JUSTIFY defines if the paragraph should be justified."
2296 (back-to-indentation)
2299 ((funcall python-fill-comment-function justify
))
2300 ;; Strings/Docstrings
2301 ((save-excursion (skip-chars-forward "\"'uUrR")
2302 (python-syntax-context 'string
))
2303 (funcall python-fill-string-function justify
))
2305 ((equal (char-after (save-excursion
2306 (back-to-indentation)
2307 (point-marker))) ?
@)
2308 (funcall python-fill-decorator-function justify
))
2310 ((or (python-syntax-context 'paren
)
2311 (looking-at (python-rx open-paren
))
2313 (skip-syntax-forward "^(" (line-end-position))
2314 (looking-at (python-rx open-paren
))))
2315 (funcall python-fill-paren-function justify
))
2318 (defun python-fill-comment (&optional justify
)
2319 "Comment fill function for `python-fill-paragraph-function'.
2320 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2321 (fill-comment-paragraph justify
))
2323 (defun python-fill-string (&optional justify
)
2324 "String fill function for `python-fill-paragraph-function'.
2325 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2326 (let ((marker (point-marker))
2327 (string-start-marker
2329 (skip-chars-forward "\"'uUrR")
2330 (goto-char (python-syntax-context 'string
))
2331 (skip-chars-forward "\"'uUrR")
2333 (reg-start (line-beginning-position))
2336 (while (python-syntax-context 'string
)
2337 (goto-char (1+ (point-marker))))
2338 (skip-chars-backward "\"'")
2340 (reg-end (line-end-position))
2341 (fill-paragraph-function))
2343 (narrow-to-region reg-start reg-end
)
2345 (goto-char string-start-marker
)
2346 (delete-region (point-marker) (progn
2347 (skip-syntax-forward "> ")
2349 (goto-char string-end-marker
)
2350 (delete-region (point-marker) (progn
2351 (skip-syntax-backward "> ")
2355 (fill-paragraph justify
))
2356 ;; If there is a newline in the docstring lets put triple
2357 ;; quote in it's own line to follow pep 8
2358 (when (save-excursion
2359 (re-search-backward "\n" string-start-marker t
))
2361 (newline-and-indent))
2362 (fill-paragraph justify
)))) t
)
2364 (defun python-fill-decorator (&optional justify
)
2365 "Decorator fill function for `python-fill-paragraph-function'.
2366 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2369 (defun python-fill-paren (&optional justify
)
2370 "Paren fill function for `python-fill-paragraph-function'.
2371 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2373 (narrow-to-region (progn
2374 (while (python-syntax-context 'paren
)
2375 (goto-char (1- (point-marker))))
2377 (line-beginning-position))
2379 (when (not (python-syntax-context 'paren
))
2381 (when (not (python-syntax-context 'paren
))
2382 (skip-syntax-backward "^)")))
2383 (while (python-syntax-context 'paren
)
2384 (goto-char (1+ (point-marker))))
2386 (let ((paragraph-start "\f\\|[ \t]*$")
2387 (paragraph-separate ",")
2388 (fill-paragraph-function))
2389 (goto-char (point-min))
2390 (fill-paragraph justify
))
2393 (python-indent-line)
2394 (goto-char (line-end-position)))) t
)
2399 (defcustom python-skeleton-autoinsert nil
2400 "Non-nil means template skeletons will be automagically inserted.
2401 This happens when pressing \"if<SPACE>\", for example, to prompt for
2407 (define-obsolete-variable-alias
2408 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
2410 (defvar python-skeleton-available
'()
2411 "Internal list of available skeletons.")
2413 (define-abbrev-table 'python-mode-abbrev-table
()
2414 "Abbrev table for Python mode."
2416 ;; Allow / inside abbrevs.
2417 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2418 ;; Only expand in code.
2419 :enable-function
(lambda ()
2421 (not (python-syntax-comment-or-string-p))
2422 python-skeleton-autoinsert
)))
2424 (defmacro python-skeleton-define
(name doc
&rest skel
)
2425 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2426 The skeleton will be bound to python-skeleton-NAME and will
2427 be added to `python-mode-abbrev-table'."
2428 (declare (indent 2))
2429 (let* ((name (symbol-name name
))
2430 (function-name (intern (concat "python-skeleton-" name
))))
2432 (define-abbrev python-mode-abbrev-table
,name
"" ',function-name
2434 (setq python-skeleton-available
2435 (cons ',function-name python-skeleton-available
))
2436 (define-skeleton ,function-name
2438 (format "Insert %s statement." name
))
2441 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
2442 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2443 The skeleton will be bound to python-skeleton-NAME."
2444 (declare (indent 2))
2445 (let* ((name (symbol-name name
))
2446 (function-name (intern (concat "python-skeleton--" name
)))
2448 "Add '%s' clause? " name
)))
2451 `(< ,(format "%s:" name
) \n \n
2453 `(define-skeleton ,function-name
2455 (format "Auxiliary skeleton for %s statement." name
))
2457 (unless (y-or-n-p ,msg
)
2461 (python-define-auxiliary-skeleton else nil
)
2463 (python-define-auxiliary-skeleton except nil
)
2465 (python-define-auxiliary-skeleton finally nil
)
2467 (python-skeleton-define if nil
2471 ("other condition, %s: "
2475 '(python-skeleton--else) | ^
)
2477 (python-skeleton-define while nil
2481 '(python-skeleton--else) | ^
)
2483 (python-skeleton-define for nil
2487 '(python-skeleton--else) | ^
)
2489 (python-skeleton-define try nil
2495 "except " str
":" \n
2498 '(python-skeleton--except)
2499 '(python-skeleton--else)
2500 '(python-skeleton--finally) | ^
)
2502 (python-skeleton-define def nil
2504 "def " str
" (" ("Parameter, %s: "
2505 (unless (equal ?\
( (char-before)) ", ")
2507 "\"\"\"" -
"\"\"\"" \n
2510 (python-skeleton-define class nil
2512 "class " str
" (" ("Inheritance, %s: "
2513 (unless (equal ?\
( (char-before)) ", ")
2517 "\"\"\"" -
"\"\"\"" \n
2520 (defun python-skeleton-add-menu-items ()
2521 "Add menu items to Python->Skeletons menu."
2522 (let ((skeletons (sort python-skeleton-available
'string
<))
2524 (dolist (skeleton skeletons
)
2526 nil
'("Python" "Skeletons")
2528 "Insert %s" (caddr (split-string (symbol-name skeleton
) "-")))
2533 (defcustom python-ffap-setup-code
2534 "def __FFAP_get_module_path(module):
2537 path = __import__(module).__file__
2538 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2543 "Python code to get a module path."
2547 (defcustom python-ffap-string-code
2548 "__FFAP_get_module_path('''%s''')\n"
2549 "Python code used to get a string with the path of a module."
2553 (defun python-ffap-module-path (module)
2554 "Function for `ffap-alist' to return path for MODULE."
2556 (and (eq major-mode
'inferior-python-mode
)
2557 (get-buffer-process (current-buffer)))
2558 (python-shell-get-process))))
2562 (python-shell-send-string-no-output
2563 (format python-ffap-string-code module
) process
)))
2565 (substring-no-properties module-file
1 -
1))))))
2567 (eval-after-load "ffap"
2569 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
2570 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
2575 (defcustom python-check-command
2577 "Command used to check a Python file."
2581 (defcustom python-check-buffer-name
2582 "*Python check: %s*"
2583 "Buffer name used for check commands."
2587 (defvar python-check-custom-command nil
2590 (defun python-check (command)
2591 "Check a Python file (default current buffer's file).
2592 Runs COMMAND, a shell command, as if by `compile'. See
2593 `python-check-command' for the default."
2595 (list (read-string "Check command: "
2596 (or python-check-custom-command
2597 (concat python-check-command
" "
2598 (shell-quote-argument
2600 (let ((name (buffer-file-name)))
2602 (file-name-nondirectory name
)))
2604 (setq python-check-custom-command command
)
2605 (save-some-buffers (not compilation-ask-about-save
) nil
)
2606 (let ((process-environment (python-shell-calculate-process-environment))
2607 (exec-path (python-shell-calculate-exec-path)))
2608 (compilation-start command nil
2610 (format python-check-buffer-name command
)))))
2615 (defcustom python-eldoc-setup-code
2616 "def __PYDOC_get_help(obj):
2619 if hasattr(obj, 'startswith'):
2620 obj = eval(obj, globals())
2621 doc = inspect.getdoc(obj)
2622 if not doc and callable(obj):
2624 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2625 target = obj.__init__
2631 args = inspect.formatargspec(
2632 *inspect.getargspec(target)
2635 doc = '{objtype} {name}{args}'.format(
2636 objtype=objtype, name=name, args=args
2639 doc = doc.splitlines()[0]
2646 "Python code to setup documentation retrieval."
2650 (defcustom python-eldoc-string-code
2651 "__PYDOC_get_help('''%s''')\n"
2652 "Python code used to get a string with the documentation of an object."
2656 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
2657 "Internal implementation to get documentation at point.
2658 If not FORCE-INPUT is passed then what
2659 `python-info-current-symbol' returns will be used. If not
2660 FORCE-PROCESS is passed what `python-shell-get-process' returns
2662 (let ((process (or force-process
(python-shell-get-process))))
2664 (error "Eldoc needs an inferior Python process running")
2665 (let ((input (or force-input
2666 (python-info-current-symbol t
))))
2668 (python-shell-send-string-no-output
2669 (format python-eldoc-string-code input
)
2672 (defun python-eldoc-function ()
2673 "`eldoc-documentation-function' for Python.
2674 For this to work the best as possible you should call
2675 `python-shell-send-buffer' from time to time so context in
2676 inferior python process is updated properly."
2677 (python-eldoc--get-doc-at-point))
2679 (defun python-eldoc-at-point (symbol)
2680 "Get help on SYMBOL using `help'.
2681 Interactively, prompt for symbol."
2683 (let ((symbol (python-info-current-symbol t
))
2684 (enable-recursive-minibuffers t
))
2685 (list (read-string (if symbol
2686 (format "Describe symbol (default %s): " symbol
)
2687 "Describe symbol: ")
2689 (message (python-eldoc--get-doc-at-point symbol
)))
2691 (add-to-list 'debug-ignored-errors
2692 "^Eldoc needs an inferior Python process running.")
2697 (defun python-info-current-defun (&optional include-type
)
2698 "Return name of surrounding function with Python compatible dotty syntax.
2699 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2700 This function is compatible to be used as
2701 `add-log-current-defun-function' since it returns nil if point is
2702 not inside a defun."
2704 (starting-indentation)
2710 (setq starting-point
(point-marker))
2711 (setq starting-indentation
(save-excursion
2712 (python-nav-beginning-of-statement)
2713 (current-indentation)))
2715 (while (python-beginning-of-defun-function 1)
2716 (when (or (< (current-indentation) starting-indentation
)
2721 (python-end-of-defun-function)
2723 (setq first-run nil
)
2724 (setq starting-indentation
(current-indentation))
2725 (looking-at python-nav-beginning-of-defun-regexp
)
2727 (if (not include-type
)
2728 (match-string-no-properties 1)
2729 (mapconcat 'identity
2731 (match-string-no-properties 0)) " "))
2734 (mapconcat (lambda (string) string
) names
"."))))
2736 (defun python-info-current-symbol (&optional replace-self
)
2737 "Return current symbol using dotty syntax.
2738 With optional argument REPLACE-SELF convert \"self\" to current
2741 (and (not (python-syntax-comment-or-string-p))
2742 (with-syntax-table python-dotty-syntax-table
2743 (let ((sym (symbol-at-point)))
2745 (substring-no-properties (symbol-name sym
))))))))
2747 (if (not replace-self
)
2749 (let ((current-defun (python-info-current-defun)))
2750 (if (not current-defun
)
2752 (replace-regexp-in-string
2753 (python-rx line-start word-start
"self" word-end ?.
)
2755 (mapconcat 'identity
2756 (butlast (split-string current-defun
"\\."))
2760 (defsubst python-info-beginning-of-block-statement-p
()
2761 "Return non-nil if current statement opens a block."
2763 (python-nav-beginning-of-statement)
2764 (looking-at (python-rx block-start
))))
2766 (defun python-info-closing-block ()
2767 "Return the point of the block the current line closes."
2768 (let ((closing-word (save-excursion
2769 (back-to-indentation)
2771 (indentation (current-indentation)))
2772 (when (member closing-word python-indent-dedenters
)
2775 (while (and (> (current-indentation) indentation
)
2777 (not (back-to-indentation))
2779 (back-to-indentation)
2781 ((not (equal indentation
(current-indentation))) nil
)
2782 ((string= closing-word
"elif")
2783 (when (member (current-word) '("if" "elif"))
2785 ((string= closing-word
"else")
2786 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2788 ((string= closing-word
"except")
2789 (when (member (current-word) '("try"))
2791 ((string= closing-word
"finally")
2792 (when (member (current-word) '("except" "else"))
2793 (point-marker))))))))
2795 (defun python-info-closing-block-message (&optional closing-block-point
)
2796 "Message the contents of the block the current line closes.
2797 With optional argument CLOSING-BLOCK-POINT use that instead of
2798 recalculating it calling `python-info-closing-block'."
2799 (let ((point (or closing-block-point
(python-info-closing-block))))
2803 (message "Closes %s" (save-excursion
2805 (back-to-indentation)
2807 (point) (line-end-position))))))))
2809 (defun python-info-line-ends-backslash-p (&optional line-number
)
2810 "Return non-nil if current line ends with backslash.
2811 With optional argument LINE-NUMBER, check that line instead."
2816 (goto-char line-number
))
2817 (while (and (not (eobp))
2818 (goto-char (line-end-position))
2819 (python-syntax-context 'paren
)
2820 (not (equal (char-before (point)) ?
\\)))
2822 (when (equal (char-before) ?
\\)
2825 (defun python-info-beginning-of-backslash (&optional line-number
)
2826 "Return the point where the backslashed line start.
2827 Optional argument LINE-NUMBER forces the line number to check against."
2832 (goto-char line-number
))
2833 (when (python-info-line-ends-backslash-p)
2834 (while (save-excursion
2835 (goto-char (line-beginning-position))
2836 (python-syntax-context 'paren
))
2838 (back-to-indentation)
2841 (defun python-info-continuation-line-p ()
2842 "Check if current line is continuation of another.
2843 When current line is continuation of another return the point
2844 where the continued line ends."
2848 (let* ((context-type (progn
2849 (back-to-indentation)
2850 (python-syntax-context-type)))
2851 (line-start (line-number-at-pos))
2852 (context-start (when context-type
2853 (python-syntax-context context-type
))))
2854 (cond ((equal context-type
'paren
)
2855 ;; Lines inside a paren are always a continuation line
2856 ;; (except the first one).
2857 (python-util-forward-comment -
1)
2859 ((member context-type
'(string comment
))
2860 ;; move forward an roll again
2861 (goto-char context-start
)
2862 (python-util-forward-comment)
2863 (python-info-continuation-line-p))
2865 ;; Not within a paren, string or comment, the only way
2866 ;; we are dealing with a continuation line is that
2867 ;; previous line contains a backslash, and this can
2868 ;; only be the previous line from current
2869 (back-to-indentation)
2870 (python-util-forward-comment -
1)
2871 (when (and (equal (1- line-start
) (line-number-at-pos))
2872 (python-info-line-ends-backslash-p))
2873 (point-marker))))))))
2875 (defun python-info-block-continuation-line-p ()
2876 "Return non-nil if current line is a continuation of a block."
2878 (when (python-info-continuation-line-p)
2880 (back-to-indentation)
2881 (when (looking-at (python-rx block-start
))
2884 (defun python-info-assignment-continuation-line-p ()
2885 "Check if current line is a continuation of an assignment.
2886 When current line is continuation of another with an assignment
2887 return the point of the first non-blank character after the
2890 (when (python-info-continuation-line-p)
2892 (back-to-indentation)
2893 (when (and (not (looking-at (python-rx block-start
)))
2894 (and (re-search-forward (python-rx not-simple-operator
2896 not-simple-operator
)
2897 (line-end-position) t
)
2898 (not (python-syntax-context-type))))
2899 (skip-syntax-forward "\s")
2902 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
2903 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
2904 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
2906 (beginning-of-line 1)
2907 (looking-at python-nav-beginning-of-defun-regexp
))))
2909 (defun python-info-current-line-comment-p ()
2910 "Check if current line is a comment line."
2911 (char-equal (or (char-after (+ (point) (current-indentation))) ?_
) ?
#))
2913 (defun python-info-current-line-empty-p ()
2914 "Check if current line is empty, ignoring whitespace."
2916 (beginning-of-line 1)
2918 (python-rx line-start
(* whitespace
)
2919 (group (* not-newline
))
2920 (* whitespace
) line-end
))
2921 (string-equal "" (match-string-no-properties 1))))
2924 ;;; Utility functions
2926 (defun python-util-position (item seq
)
2927 "Find the first occurrence of ITEM in SEQ.
2928 Return the index of the matching item, or nil if not found."
2929 (let ((member-result (member item seq
)))
2931 (- (length seq
) (length member-result
)))))
2933 ;; Stolen from org-mode
2934 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
2935 "Clone local variables from FROM-BUFFER.
2936 Optional argument REGEXP selects variables to clone and defaults
2940 (and (symbolp (car pair
))
2941 (string-match (or regexp
"^python-")
2942 (symbol-name (car pair
)))
2943 (set (make-local-variable (car pair
))
2945 (buffer-local-variables from-buffer
)))
2947 (defun python-util-forward-comment (&optional direction
)
2948 "Python mode specific version of `forward-comment'.
2949 Optional argument DIRECTION defines the direction to move to."
2950 (let ((comment-start (python-syntax-context 'comment
))
2951 (factor (if (< (or direction
0) 0)
2955 (goto-char comment-start
))
2956 (forward-comment factor
)))
2960 (define-derived-mode python-mode prog-mode
"Python"
2961 "Major mode for editing Python files.
2964 Entry to this mode calls the value of `python-mode-hook'
2965 if that value is non-nil."
2966 (set (make-local-variable 'tab-width
) 8)
2967 (set (make-local-variable 'indent-tabs-mode
) nil
)
2969 (set (make-local-variable 'comment-start
) "# ")
2970 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
2972 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
2973 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
2975 (set (make-local-variable 'forward-sexp-function
)
2976 'python-nav-forward-sexp
)
2978 (set (make-local-variable 'font-lock-defaults
)
2979 '(python-font-lock-keywords nil nil nil nil
))
2981 (set (make-local-variable 'syntax-propertize-function
)
2982 python-syntax-propertize-function
)
2984 (set (make-local-variable 'indent-line-function
)
2985 #'python-indent-line-function
)
2986 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
2988 (set (make-local-variable 'paragraph-start
) "\\s-*$")
2989 (set (make-local-variable 'fill-paragraph-function
)
2990 'python-fill-paragraph-function
)
2992 (set (make-local-variable 'beginning-of-defun-function
)
2993 #'python-beginning-of-defun-function
)
2994 (set (make-local-variable 'end-of-defun-function
)
2995 #'python-end-of-defun-function
)
2997 (add-hook 'completion-at-point-functions
2998 'python-completion-complete-at-point nil
'local
)
3000 (add-hook 'post-self-insert-hook
3001 'python-indent-post-self-insert-function nil
'local
)
3003 (set (make-local-variable 'imenu-extract-index-name-function
)
3004 #'python-info-current-defun
)
3006 (set (make-local-variable 'add-log-current-defun-function
)
3007 #'python-info-current-defun
)
3009 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
3011 (set (make-local-variable 'skeleton-further-elements
)
3013 (< '(backward-delete-char-untabify (min python-indent-offset
3015 (^
'(- (1+ (current-indentation))))))
3017 (set (make-local-variable 'eldoc-documentation-function
)
3018 #'python-eldoc-function
)
3020 (add-to-list 'hs-special-modes-alist
3021 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
3023 (python-end-of-defun-function)) nil
))
3025 (set (make-local-variable 'mode-require-final-newline
) t
)
3027 (set (make-local-variable 'outline-regexp
)
3028 (python-rx (* space
) block-start
))
3029 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
3030 (set (make-local-variable 'outline-level
)
3032 "`outline-level' function for Python mode."
3033 (1+ (/ (current-indentation) python-indent-offset
))))
3035 (python-skeleton-add-menu-items)
3037 (make-local-variable 'python-shell-internal-buffer
)
3039 (when python-indent-guess-indent-offset
3040 (python-indent-guess-indent-offset)))
3047 ;; indent-tabs-mode: nil
3050 ;;; python.el ends here