1 ;;; python.el -- Python's flying circus support for Emacs
3 ;; Copyright (C) 2010, 2011 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
10 ;; Keywords: languages
12 ;; This file is NOT part of GNU Emacs.
14 ;; python.el is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; python.el is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with python.el. If not, see <http://www.gnu.org/licenses/>.
29 ;; Major mode for editing Python files with some fontification and
30 ;; indentation bits extracted from original Dave Love's python.el
31 ;; found in GNU/Emacs.
33 ;; While it probably has less features than Dave Love's python.el and
34 ;; PSF's python-mode.el it provides the main stuff you'll need while
35 ;; keeping it simple :)
37 ;; Implements Syntax highlighting, Indentation, Movement, Shell
38 ;; interaction, Shell completion, Pdb tracking, Symbol completion,
39 ;; Skeletons, FFAP, Code Check, Eldoc, imenu.
41 ;; Syntax highlighting: Fontification of code is provided and supports
42 ;; python's triple quoted strings properly.
44 ;; Indentation: Automatic indentation with indentation cycling is
45 ;; provided, it allows you to navigate different available levels of
46 ;; indentation by hitting <tab> several times. Also when inserting a
47 ;; colon the `python-indent-electric-colon' command is invoked and
48 ;; causes the current line to be dedented automatically if needed.
50 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
51 ;; properly implemented. Also there are specialized
52 ;; `forward-sentence' and `backward-sentence' replacements
53 ;; (`python-nav-forward-sentence', `python-nav-backward-sentence'
54 ;; respectively). Extra functions `python-nav-sentence-start' and
55 ;; `python-nav-sentence-end' are included to move to the beginning and
56 ;; to the end of a setence while taking care of multiline definitions.
58 ;; Shell interaction: is provided and allows you easily execute any
59 ;; block of code of your current buffer in an inferior Python process.
61 ;; Shell completion: hitting tab will try to complete the current
62 ;; word. Shell completion is implemented in a manner that if you
63 ;; change the `python-shell-interpreter' to any other (for example
64 ;; IPython) it should be easy to integrate another way to calculate
65 ;; completions. You just need to specify your custom
66 ;; `python-shell-completion-setup-code' and
67 ;; `python-shell-completion-string-code'.
69 ;; Here is a complete example of the settings you would use for
73 ;; python-shell-interpreter "ipython"
74 ;; python-shell-interpreter-args ""
75 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
76 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
77 ;; python-shell-completion-setup-code ""
78 ;; python-shell-completion-string-code
79 ;; "';'.join(__IP.complete('''%s'''))\n")
81 ;; Please note that the default completion system depends on the
82 ;; readline module, so if you are using some Operating System that
83 ;; bundles Python without it (like Windows) just install the
84 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
85 ;; you should be good to go.
87 ;; The shell also contains support for virtualenvs and other special
88 ;; environment modification thanks to
89 ;; `python-shell-process-environment' and `python-shell-exec-path'.
90 ;; These two variables allows you to modify execution paths and
91 ;; enviroment variables to make easy for you to setup virtualenv rules
92 ;; or behaviors modifications when running shells. Here is an example
93 ;; of how to make shell processes to be run using the /path/to/env/
96 ;; (setq python-shell-process-environment
98 ;; (format "PATH=%s" (mapconcat
101 ;; (cons (getenv "PATH")
102 ;; '("/path/to/env/bin/")))
104 ;; "VIRTUAL_ENV=/path/to/env/"))
105 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
107 ;; Pdb tracking: when you execute a block of code that contains some
108 ;; call to pdb (or ipdb) it will prompt the block of code and will
109 ;; follow the execution of pdb marking the current line with an arrow.
111 ;; Symbol completion: you can complete the symbol at point. It uses
112 ;; the shell completion in background so you should run
113 ;; `python-shell-send-buffer' from time to time to get better results.
115 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
116 ;; def, for, if, try and while. These skeletons are integrated with
117 ;; dabbrev. If you have `dabbrev-mode' activated and
118 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
119 ;; the name of any of those defined and hit SPC, they will be
120 ;; automatically expanded.
122 ;; FFAP: You can find the filename for a given module when using ffap
123 ;; out of the box. This feature needs an inferior python shell
126 ;; Code check: Check the current file for errors with `python-check'
127 ;; using the program defined in `python-check-command'.
129 ;; Eldoc: returns documentation for object at point by using the
130 ;; inferior python subprocess to inspect its documentation. As you
131 ;; might guessed you should run `python-shell-send-buffer' from time
132 ;; to time to get better results too.
134 ;; imenu: This mode supports imenu. It builds a plain or tree menu
135 ;; depending on the value of `python-imenu-make-tree'. Also you can
136 ;; customize if menu items should include its type using
137 ;; `python-imenu-include-defun-type'.
139 ;; If you used python-mode.el you probably will miss auto-indentation
140 ;; when inserting newlines. To achieve the same behavior you have
143 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
145 ;; 2) Add the following hook in your .emacs:
147 ;; (add-hook 'python-mode-hook
149 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
151 ;; I'd recommend the first one since you'll get the same behavior for
152 ;; all modes out-of-the-box.
156 ;; Add this to your .emacs:
158 ;; (add-to-list 'load-path "/folder/containing/file")
163 ;; Ordered by priority:
165 ;; Better decorator support for beginning of defun
167 ;; Review code and cleanup
171 (require 'ansi-color)
176 ;; Avoid compiler warnings
177 (defvar view-return-to-alist)
178 (defvar compilation-error-regexp-alist)
179 (defvar outline-heading-end-regexp))
181 (autoload 'comint-mode "comint")
184 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
186 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
189 "Python Language's flying circus support for Emacs."
192 :link '(emacs-commentary-link "python"))
197 (defvar python-mode-map
198 (let ((map (make-sparse-keymap)))
200 (substitute-key-definition 'backward-sentence
201 'python-nav-backward-sentence
203 (substitute-key-definition 'forward-sentence
204 'python-nav-forward-sentence
207 (define-key map "\177" 'python-indent-dedent-line-backspace)
208 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
209 (define-key map "\C-c<" 'python-indent-shift-left)
210 (define-key map "\C-c>" 'python-indent-shift-right)
211 (define-key map ":" 'python-indent-electric-colon)
213 (define-key map "\C-c\C-tc" 'python-skeleton-class)
214 (define-key map "\C-c\C-td" 'python-skeleton-def)
215 (define-key map "\C-c\C-tf" 'python-skeleton-for)
216 (define-key map "\C-c\C-ti" 'python-skeleton-if)
217 (define-key map "\C-c\C-tt" 'python-skeleton-try)
218 (define-key map "\C-c\C-tw" 'python-skeleton-while)
220 (define-key map "\C-c\C-s" 'python-shell-send-string)
221 (define-key map "\C-c\C-r" 'python-shell-send-region)
222 (define-key map "\C-\M-x" 'python-shell-send-defun)
223 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
224 (define-key map "\C-c\C-l" 'python-shell-send-file)
225 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
226 ;; Some util commands
227 (define-key map "\C-c\C-v" 'python-check)
228 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
230 (substitute-key-definition 'complete-symbol 'completion-at-point
232 (easy-menu-define python-menu map "Python Mode menu"
234 :help "Python-specific Features"
235 ["Shift region left" python-indent-shift-left :active mark-active
236 :help "Shift region left by a single indentation step"]
237 ["Shift region right" python-indent-shift-right :active mark-active
238 :help "Shift region right by a single indentation step"]
240 ["Mark def/class" mark-defun
241 :help "Mark outermost definition around point"]
243 ["Start of def/class" beginning-of-defun
244 :help "Go to start of outermost definition around point"]
245 ["End of def/class" end-of-defun
246 :help "Go to end of definition around point"]
250 ["Start interpreter" run-python
251 :help "Run inferior Python process in a separate buffer"]
252 ["Switch to shell" python-shell-switch-to-shell
253 :help "Switch to running inferior Python process"]
254 ["Eval string" python-shell-send-string
255 :help "Eval string in inferior Python session"]
256 ["Eval buffer" python-shell-send-buffer
257 :help "Eval buffer in inferior Python session"]
258 ["Eval region" python-shell-send-region
259 :help "Eval region in inferior Python session"]
260 ["Eval defun" python-shell-send-defun
261 :help "Eval defun in inferior Python session"]
262 ["Eval file" python-shell-send-file
263 :help "Eval file in inferior Python session"]
264 ["Debugger" pdb :help "Run pdb under GUD"]
266 ["Check file" python-check
267 :help "Check file for errors"]
268 ["Help on symbol" python-eldoc-at-point
269 :help "Get help on symbol at point"]
270 ["Complete symbol" completion-at-point
271 :help "Complete symbol before point"]))
273 "Keymap for `python-mode'.")
276 ;;; Python specialized rx
279 (defconst python-rx-constituents
281 `(block-start . ,(rx symbol-start
282 (or "def" "class" "if" "elif" "else" "try"
283 "except" "finally" "for" "while" "with")
285 `(decorator . ,(rx line-start (* space) ?@ (any letter ?_)
287 `(defun . ,(rx symbol-start (or "def" "class") symbol-end))
288 `(symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
289 `(open-paren . ,(rx (or "{" "[" "(")))
290 `(close-paren . ,(rx (or "}" "]" ")")))
291 `(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
292 `(not-simple-operator . ,(rx (not (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
293 `(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
294 "=" "%" "**" "//" "<<" ">>" "<=" "!="
295 "==" ">=" "is" "not")))
296 `(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
297 ">>=" "<<=" "&=" "^=" "|="))))
298 "Additional Python specific sexps for `python-rx'"))
300 (defmacro python-rx (&rest regexps)
301 "Python mode specialized rx macro which supports common python named REGEXPS."
302 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
303 (cond ((null regexps)
306 (rx-to-string `(and ,@regexps) t))
308 (rx-to-string (car regexps) t)))))
311 ;;; Font-lock and syntax
313 (defvar python-font-lock-keywords
316 (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
317 "assert" "else" "if" "pass" "yield" "break" "except" "import"
318 "print" "class" "exec" "in" "raise" "continue" "finally" "is"
319 "return" "def" "for" "lambda" "try" "self")
322 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
323 (1 font-lock-function-name-face))
325 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
326 (1 font-lock-type-face))
329 ;; copyright, license, credits, quit, exit are added by the
330 ;; site module and since they are not intended to be used in
331 ;; programs they are not added here either.
332 (or "None" "True" "False" "Ellipsis" "__debug__" "NotImplemented")
333 symbol-end) . font-lock-constant-face)
335 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
336 (0+ "." (1+ (or word ?_)))))
337 (1 font-lock-type-face))
338 ;; Builtin Exceptions
340 (or "ArithmeticError" "AssertionError" "AttributeError"
341 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
342 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
343 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
344 "ImportWarning" "IndentationError" "IndexError" "KeyError"
345 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
346 "NotImplementedError" "OSError" "OverflowError"
347 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
348 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
349 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
350 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
351 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
352 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
353 symbol-end) . font-lock-type-face)
356 (or "_" "__doc__" "__import__" "__name__" "__package__" "abs" "all"
357 "any" "apply" "basestring" "bin" "bool" "buffer" "bytearray"
358 "bytes" "callable" "chr" "classmethod" "cmp" "coerce" "compile"
359 "complex" "delattr" "dict" "dir" "divmod" "enumerate" "eval"
360 "execfile" "file" "filter" "float" "format" "frozenset"
361 "getattr" "globals" "hasattr" "hash" "help" "hex" "id" "input"
362 "int" "intern" "isinstance" "issubclass" "iter" "len" "list"
363 "locals" "long" "map" "max" "min" "next" "object" "oct" "open"
364 "ord" "pow" "print" "property" "range" "raw_input" "reduce"
365 "reload" "repr" "reversed" "round" "set" "setattr" "slice"
366 "sorted" "staticmethod" "str" "sum" "super" "tuple" "type"
367 "unichr" "unicode" "vars" "xrange" "zip")
368 symbol-end) . font-lock-builtin-face)
370 ;; support for a = b = c = 5
372 (let ((re (python-rx (group (+ (any word ?. ?_)))
373 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
374 assignment-operator)))
375 (when (re-search-forward re limit t)
376 (while (and (python-info-ppss-context 'paren)
377 (re-search-forward re limit t)))
378 (if (and (not (python-info-ppss-context 'paren))
379 (not (equal (char-after (point-marker)) ?=)))
381 (set-match-data nil)))))
382 (1 font-lock-variable-name-face nil nil))
383 ;; support for a, b, c = (1, 2, 3)
385 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
386 (* ?, (* space) (+ (any word ?. ?_)) (* space))
387 ?, (* space) (+ (any word ?. ?_)) (* space)
388 assignment-operator)))
389 (when (and (re-search-forward re limit t)
390 (goto-char (nth 3 (match-data))))
391 (while (and (python-info-ppss-context 'paren)
392 (re-search-forward re limit t))
393 (goto-char (nth 3 (match-data))))
394 (if (not (python-info-ppss-context 'paren))
396 (set-match-data nil)))))
397 (1 font-lock-variable-name-face nil nil))))
399 ;; Fixme: Is there a better way?
400 (defconst python-font-lock-syntactic-keywords
401 ;; First avoid a sequence preceded by an odd number of backslashes.
402 `((,(rx (not (any ?\\))
403 ?\\ (* (and ?\\ ?\\))
404 (group (syntax string-quote))
407 (2 ,(string-to-syntax "\""))) ; dummy
408 (,(rx (group (optional (any "uUrR"))) ; prefix gets syntax property
409 (optional (any "rR")) ; possible second prefix
410 (group (syntax string-quote)) ; maybe gets property
411 (backref 2) ; per first quote
412 (group (backref 2))) ; maybe gets property
413 (1 (python-quote-syntax 1))
414 (2 (python-quote-syntax 2))
415 (3 (python-quote-syntax 3))))
416 "Make outer chars of triple-quote strings into generic string delimiters.")
418 (defun python-quote-syntax (n)
419 "Put `syntax-table' property correctly on triple quote.
420 Used for syntactic keywords. N is the match number (1, 2 or 3)."
421 ;; Given a triple quote, we have to check the context to know
422 ;; whether this is an opening or closing triple or whether it's
423 ;; quoted anyhow, and should be ignored. (For that we need to do
424 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
425 ;; to use it here despite initial worries.) We also have to sort
426 ;; out a possible prefix -- well, we don't _have_ to, but I think it
427 ;; should be treated as part of the string.
430 ;; ur"""ar""" x='"' # """
433 ;; x '"""' x """ \"""" x
435 (goto-char (match-beginning 0))
437 ;; Consider property for the last char if in a fenced string.
439 (let* ((font-lock-syntactic-keywords nil)
440 (syntax (syntax-ppss)))
441 (when (eq t (nth 3 syntax)) ; after unclosed fence
442 (goto-char (nth 8 syntax)) ; fence position
443 (skip-chars-forward "uUrR") ; skip any prefix
444 ;; Is it a matching sequence?
445 (if (eq (char-after) (char-after (match-beginning 2)))
446 (eval-when-compile (string-to-syntax "|"))))))
447 ;; Consider property for initial char, accounting for prefixes.
448 ((or (and (= n 2) ; leading quote (not prefix)
449 (= (match-beginning 1) (match-end 1))) ; prefix is null
450 (and (= n 1) ; prefix
451 (/= (match-beginning 1) (match-end 1)))) ; non-empty
452 (let ((font-lock-syntactic-keywords nil))
453 (unless (eq 'string (syntax-ppss-context (syntax-ppss)))
454 (eval-when-compile (string-to-syntax "|")))))
455 ;; Otherwise (we're in a non-matching string) the property is
459 (defvar python-mode-syntax-table
460 (let ((table (make-syntax-table)))
461 ;; Give punctuation syntax to ASCII that normally has symbol
462 ;; syntax or has word syntax and isn't a letter.
463 (let ((symbol (string-to-syntax "_"))
464 (sst (standard-syntax-table)))
467 (if (equal symbol (aref sst i))
468 (modify-syntax-entry i "." table)))))
469 (modify-syntax-entry ?$ "." table)
470 (modify-syntax-entry ?% "." table)
472 (modify-syntax-entry ?# "<" table)
473 (modify-syntax-entry ?\n ">" table)
474 (modify-syntax-entry ?' "\"" table)
475 (modify-syntax-entry ?` "$" table)
477 "Syntax table for Python files.")
479 (defvar python-dotty-syntax-table
480 (let ((table (make-syntax-table python-mode-syntax-table)))
481 (modify-syntax-entry ?. "w" table)
482 (modify-syntax-entry ?_ "w" table)
484 "Dotty syntax table for Python files.
485 It makes underscores and dots word constituent chars.")
490 (defcustom python-indent-offset 4
491 "Default indentation offset for Python."
496 (defcustom python-indent-guess-indent-offset t
497 "Non-nil tells Python mode to guess `python-indent-offset' value."
501 (defvar python-indent-current-level 0
502 "Current indentation level `python-indent-line-function' is using.")
504 (defvar python-indent-levels '(0)
505 "Levels of indentation available for `python-indent-line-function'.")
507 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
508 "List of words that should be dedented.
509 These make `python-indent-calculate-indentation' subtract the value of
510 `python-indent-offset'.")
512 (defun python-indent-guess-indent-offset ()
513 "Guess and set `python-indent-offset' for the current buffer."
517 (goto-char (point-min))
519 (while (and (not found-block)
521 (python-rx line-start block-start) nil t))
522 (when (and (not (python-info-ppss-context 'string))
523 (not (python-info-ppss-context 'comment))
525 (goto-char (line-end-position))
526 (forward-comment -9999)
527 (eq ?: (char-before))))
528 (setq found-block t)))
529 (if (not found-block)
530 (message "Can't guess python-indent-offset, using defaults: %s"
531 python-indent-offset)
533 (goto-char (line-end-position))
534 (python-info-continuation-line-p))
538 (forward-comment 9999)
539 (let ((indent-offset (current-indentation)))
540 (when (> indent-offset 0)
541 (setq python-indent-offset indent-offset))))))))
543 (defun python-indent-context ()
544 "Get information on indentation context.
545 Context information is returned with a cons with the form:
548 Where status can be any of the following symbols:
549 * inside-paren: If point in between (), {} or []
550 * inside-string: If point is inside a string
551 * after-backslash: Previous line ends in a backslash
552 * after-beginning-of-block: Point is after beginning of block
553 * after-line: Point is after normal line
554 * no-indent: Point is at beginning of buffer or other special case
555 START is the buffer position where the sexp starts."
558 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
562 ;; Beginning of buffer
564 (goto-char (line-beginning-position))
568 ((setq start (python-info-ppss-context 'paren ppss))
571 ((setq start (python-info-ppss-context 'string ppss))
574 ((setq start (when (not (or (python-info-ppss-context 'string ppss)
575 (python-info-ppss-context 'comment ppss)))
576 (let ((line-beg-pos (line-beginning-position)))
577 (when (eq ?\\ (char-before (1- line-beg-pos)))
578 (- line-beg-pos 2)))))
580 ;; After beginning of block
581 ((setq start (save-excursion
582 (let ((block-regexp (python-rx block-start))
583 (block-start-line-end ":[[:space:]]*$"))
584 (back-to-indentation)
585 (while (and (forward-comment -9999) (not (bobp))))
586 (back-to-indentation)
587 (when (or (python-info-continuation-line-p)
588 (and (not (looking-at block-regexp))
592 (line-end-position) t))))
593 (while (and (forward-line -1)
594 (python-info-continuation-line-p)
596 (when (not (looking-at block-regexp))
598 (back-to-indentation)
599 (when (and (looking-at block-regexp)
600 (or (re-search-forward
602 (line-end-position) t)
603 (python-info-continuation-line-p)))
605 'after-beginning-of-block)
607 ((setq start (save-excursion
608 (while (and (forward-comment -9999) (not (bobp))))
609 (python-nav-sentence-start)
616 (defun python-indent-calculate-indentation ()
617 "Calculate correct indentation offset for the current line."
618 (let* ((indentation-context (python-indent-context))
619 (context-status (car indentation-context))
620 (context-start (cdr indentation-context)))
626 ('after-beginning-of-block
627 (goto-char context-start)
628 (+ (current-indentation) python-indent-offset))
632 (goto-char context-start)
633 (current-indentation))
635 (back-to-indentation)
636 (looking-at (regexp-opt python-indent-dedenters)))
640 (goto-char context-start)
641 (current-indentation))
643 (let* ((block-continuation
646 (python-info-block-continuation-line-p)))
647 (assignment-continuation
650 (python-info-assignment-continuation-line-p)))
653 (back-to-indentation)
654 (when (looking-at "\\.")
656 (goto-char (line-end-position))
657 (while (and (re-search-backward "\\." (line-beginning-position) t)
658 (or (python-info-ppss-context 'comment)
659 (python-info-ppss-context 'string)
660 (python-info-ppss-context 'paren))))
661 (if (and (looking-at "\\.")
662 (not (or (python-info-ppss-context 'comment)
663 (python-info-ppss-context 'string)
664 (python-info-ppss-context 'paren))))
666 (+ (current-indentation) python-indent-offset)))))
671 (goto-char block-continuation)
673 (python-rx block-start (* space))
674 (line-end-position) t)
676 (assignment-continuation
677 (goto-char assignment-continuation)
679 (python-rx simple-operator)
680 (line-end-position) t)
683 (python-rx (* space))
684 (line-end-position) t)
687 (goto-char context-start)
690 (back-to-indentation)
692 "\\(?:return\\|from\\|import\\)\s+")))
693 (current-indentation)
694 (+ (current-indentation)
696 (match-string-no-properties 0))))))))
700 (skip-syntax-forward "\s" (line-end-position))
701 (when (and (looking-at (regexp-opt '(")" "]" "}")))
702 (not (forward-char 1))
703 (not (python-info-ppss-context 'paren)))
704 (goto-char context-start)
705 (back-to-indentation)
709 (goto-char context-start)
713 (line-beginning-position)
715 (forward-comment 9999))
717 (+ (current-indentation) python-indent-offset)
718 (forward-comment 9999)
721 (back-to-indentation)
722 (looking-at (regexp-opt '(")" "]" "}"))))
726 (defun python-indent-calculate-levels ()
727 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
728 (let* ((indentation (python-indent-calculate-indentation))
729 (remainder (% indentation python-indent-offset))
730 (steps (/ (- indentation remainder) python-indent-offset)))
731 (setq python-indent-levels (list 0))
732 (dotimes (step steps)
733 (push (* python-indent-offset (1+ step)) python-indent-levels))
734 (when (not (eq 0 remainder))
735 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
736 (setq python-indent-levels (nreverse python-indent-levels))
737 (setq python-indent-current-level (1- (length python-indent-levels)))))
739 (defun python-indent-toggle-levels ()
740 "Toggle `python-indent-current-level' over `python-indent-levels'."
741 (setq python-indent-current-level (1- python-indent-current-level))
742 (when (< python-indent-current-level 0)
743 (setq python-indent-current-level (1- (length python-indent-levels)))))
745 (defun python-indent-line (&optional force-toggle)
746 "Internal implementation of `python-indent-line-function'.
747 Uses the offset calculated in
748 `python-indent-calculate-indentation' and available levels
749 indicated by the variable `python-indent-levels' to set the
752 When the variable `last-command' is equal to
753 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
754 levels indicated in the variable `python-indent-levels' by
755 setting the current level in the variable
756 `python-indent-current-level'.
758 When the variable `last-command' is not equal to
759 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
760 possible indentation levels and saves it in the variable
761 `python-indent-levels'. Afterwards it sets the variable
762 `python-indent-current-level' correctly so offset is equal
763 to (`nth' `python-indent-current-level' `python-indent-levels')"
764 (if (or (and (eq this-command 'indent-for-tab-command)
765 (eq last-command this-command))
767 (if (not (equal python-indent-levels '(0)))
768 (python-indent-toggle-levels)
769 (python-indent-calculate-levels))
770 (python-indent-calculate-levels))
772 (delete-horizontal-space)
773 (indent-to (nth python-indent-current-level python-indent-levels))
776 (let ((closing-block-point (python-info-closing-block)))
777 (when closing-block-point
778 (message "Closes %s" (buffer-substring
781 (goto-char closing-block-point)
782 (line-end-position))))))))
784 (defun python-indent-line-function ()
785 "`indent-line-function' for Python mode.
786 See `python-indent-line' for details."
787 (python-indent-line))
789 (defun python-indent-dedent-line ()
790 "De-indent current line."
792 (when (and (not (or (python-info-ppss-context 'string)
793 (python-info-ppss-context 'comment)))
794 (<= (point-marker) (save-excursion
795 (back-to-indentation)
797 (> (current-column) 0))
798 (python-indent-line t)
801 (defun python-indent-dedent-line-backspace (arg)
802 "De-indent current line.
803 Argument ARG is passed to `backward-delete-char-untabify' when
804 point is not in between the indentation."
806 (when (not (python-indent-dedent-line))
807 (backward-delete-char-untabify arg)))
808 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
810 (defun python-indent-region (start end)
811 "Indent a python region automagically.
813 Called from a program, START and END specify the region to indent."
814 (let ((deactivate-mark nil))
817 (setq end (point-marker))
819 (or (bolp) (forward-line 1))
820 (while (< (point) end)
821 (or (and (bolp) (eolp))
824 (back-to-indentation)
825 (setq word (current-word))
829 (delete-horizontal-space)
830 (indent-to (python-indent-calculate-indentation)))))
832 (move-marker end nil))))
834 (defun python-indent-shift-left (start end &optional count)
835 "Shift lines contained in region START END by COUNT columns to the left.
836 COUNT defaults to `python-indent-offset'. If region isn't
837 active, the current line is shifted. The shifted region includes
838 the lines in which START and END lie. An error is signaled if
839 any lines in the region are indented less than COUNT columns."
842 (list (region-beginning) (region-end) current-prefix-arg)
843 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
845 (setq count (prefix-numeric-value count))
846 (setq count python-indent-offset))
848 (let ((deactivate-mark nil))
851 (while (< (point) end)
852 (if (and (< (current-indentation) count)
853 (not (looking-at "[ \t]*$")))
854 (error "Can't shift all lines enough"))
856 (indent-rigidly start end (- count))))))
858 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
860 (defun python-indent-shift-right (start end &optional count)
861 "Shift lines contained in region START END by COUNT columns to the left.
862 COUNT defaults to `python-indent-offset'. If region isn't
863 active, the current line is shifted. The shifted region includes
864 the lines in which START and END lie."
867 (list (region-beginning) (region-end) current-prefix-arg)
868 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
869 (let ((deactivate-mark nil))
871 (setq count (prefix-numeric-value count))
872 (setq count python-indent-offset))
873 (indent-rigidly start end count)))
875 (defun python-indent-electric-colon (arg)
876 "Insert a colon and maybe de-indent the current line.
877 With numeric ARG, just insert that many colons. With
878 \\[universal-argument], just insert a single colon."
880 (self-insert-command (if (not (integerp arg)) 1 arg))
883 (not (equal ?: (char-after (- (point-marker) 2))))
884 (not (or (python-info-ppss-context 'string)
885 (python-info-ppss-context 'comment))))
886 (let ((indentation (current-indentation))
887 (calculated-indentation (python-indent-calculate-indentation)))
888 (when (> indentation calculated-indentation)
890 (indent-line-to calculated-indentation)
891 (when (not (python-info-closing-block))
892 (indent-line-to indentation)))))))
893 (put 'python-indent-electric-colon 'delete-selection t)
898 (defvar python-nav-beginning-of-defun-regexp
899 (python-rx line-start (* space) defun (+ space) (group symbol-name))
900 "Regular expresion matching beginning of class or function.
901 The name of the defun should be grouped so it can be retrieved
902 via `match-string'.")
904 (defun python-nav-beginning-of-defun (&optional nodecorators)
905 "Move point to `beginning-of-defun'.
906 When NODECORATORS is non-nil decorators are not included. This
907 is the main part of`python-beginning-of-defun-function'
908 implementation. Return non-nil if point is moved to the
909 `beginning-of-defun'."
910 (let ((indent-pos (save-excursion
911 (back-to-indentation)
916 (when (not nodecorators)
917 (when (save-excursion
919 (looking-at (python-rx decorator)))
920 (while (and (not (bobp))
922 (looking-at (python-rx decorator))))
923 (when (not (bobp)) (forward-line 1)))))))
924 (if (and (> (point) indent-pos)
926 (goto-char (line-beginning-position))
927 (looking-at python-nav-beginning-of-defun-regexp)))
929 (goto-char (line-beginning-position))
930 (funcall include-decorators)
932 (goto-char (line-beginning-position))
933 (when (re-search-backward python-nav-beginning-of-defun-regexp nil t)
935 (goto-char (or (python-info-ppss-context 'string) (point)))
936 (funcall include-decorators))
939 (defun python-beginning-of-defun-function (&optional arg nodecorators)
940 "Move point to the beginning of def or class.
941 With positive ARG move that number of functions forward. With
942 negative do the same but backwards. When NODECORATORS is non-nil
943 decorators are not included. Return non-nil if point is moved to the
944 `beginning-of-defun'."
945 (when (or (null arg) (= arg 0)) (setq arg 1))
947 (dotimes (i arg (python-nav-beginning-of-defun nodecorators)))
949 (dotimes (i (- arg) found)
950 (python-end-of-defun-function)
951 (forward-comment 9999)
952 (goto-char (line-end-position))
955 (python-nav-beginning-of-defun nodecorators)))))))
957 (defun python-end-of-defun-function ()
958 "Move point to the end of def or class.
959 Returns nil if point is not in a def or class."
961 (let ((beg-defun-indent)
962 (decorator-regexp "[[:space:]]*@"))
963 (when (looking-at decorator-regexp)
964 (while (and (not (eobp))
966 (looking-at decorator-regexp))))
967 (when (not (looking-at python-nav-beginning-of-defun-regexp))
968 (python-beginning-of-defun-function))
969 (setq beg-defun-indent (current-indentation))
971 (while (and (forward-line 1)
973 (or (not (current-word))
974 (> (current-indentation) beg-defun-indent))))
975 (forward-comment 9999)
976 (goto-char (line-beginning-position))))
978 (defun python-nav-sentence-start ()
979 "Move to start of current sentence."
981 (while (and (not (back-to-indentation))
986 (python-info-line-ends-backslash-p))
987 (python-info-ppss-context 'string)
988 (python-info-ppss-context 'paren))
989 (forward-line -1)))))
991 (defun python-nav-sentence-end ()
992 "Move to end of current sentence."
994 (while (and (goto-char (line-end-position))
997 (python-info-line-ends-backslash-p)
998 (python-info-ppss-context 'string)
999 (python-info-ppss-context 'paren))
1000 (forward-line 1)))))
1002 (defun python-nav-backward-sentence (&optional arg)
1003 "Move backward to start of sentence. With ARG, do it arg times.
1004 See `python-nav-forward-sentence' for more information."
1006 (or arg (setq arg 1))
1007 (python-nav-forward-sentence (- arg)))
1009 (defun python-nav-forward-sentence (&optional arg)
1010 "Move forward to next end of sentence. With ARG, repeat.
1011 With negative argument, move backward repeatedly to start of sentence."
1013 (or arg (setq arg 1))
1015 (forward-comment 9999)
1016 (python-nav-sentence-end)
1018 (setq arg (1- arg)))
1020 (python-nav-sentence-end)
1021 (forward-comment -9999)
1022 (python-nav-sentence-start)
1024 (setq arg (1+ arg))))
1027 ;;; Shell integration
1029 (defvar python-shell-buffer-name "Python"
1030 "Default buffer name for Python interpreter.")
1032 (defcustom python-shell-interpreter "python"
1033 "Default Python interpreter for shell."
1038 (defcustom python-shell-interpreter-args "-i"
1039 "Default arguments for the Python interpreter."
1044 (defcustom python-shell-prompt-regexp ">>> "
1045 "Regular Expression matching top\-level input prompt of python shell.
1046 It should not contain a caret (^) at the beginning."
1051 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1052 "Regular Expression matching block input prompt of python shell.
1053 It should not contain a caret (^) at the beginning."
1058 (defcustom python-shell-prompt-output-regexp nil
1059 "Regular Expression matching output prompt of python shell.
1060 It should not contain a caret (^) at the beginning."
1065 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1066 "Regular Expression matching pdb input prompt of python shell.
1067 It should not contain a caret (^) at the beginning."
1072 (defcustom python-shell-send-setup-max-wait 5
1073 "Seconds to wait for process output before code setup.
1074 If output is received before the especified time then control is
1075 returned in that moment and not after waiting."
1080 (defcustom python-shell-process-environment nil
1081 "List of enviroment variables for Python shell.
1082 This variable follows the same rules as `process-enviroment'
1083 since it merges with it before the process creation routines are
1084 called. When this variable is nil, the Python shell is run with
1085 the default `process-enviroment'."
1086 :type '(repeat string)
1090 (defcustom python-shell-exec-path nil
1091 "List of path to search for binaries.
1092 This variable follows the same rules as `exec-path' since it
1093 merges with it before the process creation routines are called.
1094 When this variable is nil, the Python shell is run with the
1095 default `exec-path'."
1096 :type '(repeat string)
1100 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1101 python-ffap-setup-code
1102 python-eldoc-setup-code)
1103 "List of code run by `python-shell-send-setup-codes'.
1104 Each variable can contain either a simple string with the code to
1105 execute or a cons with the form (CODE . DESCRIPTION), where CODE
1106 is a string with the code to execute and DESCRIPTION is the
1108 :type '(repeat symbol)
1112 (defcustom python-shell-compilation-regexp-alist
1113 `((,(rx line-start (1+ (any " \t")) "File \""
1114 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1115 "\", line " (group (1+ digit)))
1117 (,(rx " in file " (group (1+ not-newline)) " on line "
1120 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1121 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1123 "`compilation-error-regexp-alist' for inferior Python."
1124 :type '(alist string)
1127 (defun python-shell-get-process-name (dedicated)
1128 "Calculate the appropiate process name for inferior Python process.
1129 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1130 returns a string with the form
1131 `python-shell-buffer-name'[variable `buffer-file-name'] else
1132 returns the value of `python-shell-buffer-name'. After
1133 calculating the process name adds the buffer name for the process
1134 in the `same-window-buffer-names' list."
1138 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1139 (format "%s" python-shell-buffer-name))))
1140 (add-to-list 'same-window-buffer-names (purecopy
1141 (format "*%s*" process-name)))
1144 (defun python-shell-parse-command ()
1145 "Calculate the string used to execute the inferior Python process."
1146 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1148 (defun python-comint-output-filter-function (output)
1149 "Hook run after content is put into comint buffer.
1150 OUTPUT is a string with the contents of the buffer."
1151 (ansi-color-filter-apply output))
1153 (defvar inferior-python-mode-current-file nil
1154 "Current file from which a region was sent.")
1155 (make-variable-buffer-local 'inferior-python-mode-current-file)
1157 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1158 "Major mode for Python inferior process.
1159 Runs a Python interpreter as a subprocess of Emacs, with Python
1160 I/O through an Emacs buffer. Variables
1161 `python-shell-interpreter' and `python-shell-interpreter-args'
1162 controls which Python interpreter is run. Variables
1163 `python-shell-prompt-regexp',
1164 `python-shell-prompt-output-regexp',
1165 `python-shell-prompt-block-regexp',
1166 `python-shell-completion-setup-code',
1167 `python-shell-completion-string-code', `python-eldoc-setup-code',
1168 `python-eldoc-string-code', `python-ffap-setup-code' and
1169 `python-ffap-string-code' can customize this mode for different
1170 Python interpreters.
1172 You can also add additional setup code to be run at
1173 initialization of the interpreter via `python-shell-setup-codes'
1176 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1177 (set-syntax-table python-mode-syntax-table)
1178 (setq mode-line-process '(":%s"))
1179 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1180 python-shell-prompt-regexp
1181 python-shell-prompt-block-regexp
1182 python-shell-prompt-pdb-regexp))
1183 (make-local-variable 'comint-output-filter-functions)
1184 (add-hook 'comint-output-filter-functions
1185 'python-comint-output-filter-function)
1186 (add-hook 'comint-output-filter-functions
1187 'python-pdbtrack-comint-output-filter-function)
1188 (set (make-local-variable 'compilation-error-regexp-alist)
1189 python-shell-compilation-regexp-alist)
1190 (define-key inferior-python-mode-map [remap complete-symbol]
1191 'completion-at-point)
1192 (add-hook 'completion-at-point-functions
1193 'python-shell-completion-complete-at-point nil 'local)
1194 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1195 'python-shell-completion-complete-at-point)
1196 (define-key inferior-python-mode-map (kbd "<tab>")
1197 'python-shell-completion-complete-or-indent)
1198 (compilation-shell-minor-mode 1))
1200 (defun run-python (dedicated cmd)
1201 "Run an inferior Python process.
1202 Input and output via buffer named after
1203 `python-shell-buffer-name'. If there is a process already
1204 running in that buffer, just switch to it.
1205 With argument, allows you to define DEDICATED, so a dedicated
1206 process for the current buffer is open, and define CMD so you can
1207 edit the command used to call the interpreter (default is value
1208 of `python-shell-interpreter' and arguments defined in
1209 `python-shell-interpreter-args'). Runs the hook
1210 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1212 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1214 (if current-prefix-arg
1216 (y-or-n-p "Make dedicated process? ")
1217 (read-string "Run Python: " (python-shell-parse-command)))
1218 (list nil (python-shell-parse-command))))
1219 (let* ((proc-name (python-shell-get-process-name dedicated))
1220 (proc-buffer-name (format "*%s*" proc-name))
1221 (process-environment
1222 (if python-shell-process-environment
1223 (python-util-merge 'list python-shell-process-environment
1224 process-environment 'string=)
1225 process-environment))
1227 (if python-shell-exec-path
1228 (python-util-merge 'list python-shell-exec-path
1231 (when (not (comint-check-proc proc-buffer-name))
1232 (let ((cmdlist (split-string-and-unquote cmd)))
1234 (apply 'make-comint proc-name (car cmdlist) nil
1236 (inferior-python-mode)))
1237 (pop-to-buffer proc-buffer-name))
1240 (defun python-shell-get-process ()
1241 "Get inferior Python process for current buffer and return it."
1242 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1243 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1244 (global-proc-name (python-shell-get-process-name nil))
1245 (global-proc-buffer-name (format "*%s*" global-proc-name))
1246 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1247 (global-running (comint-check-proc global-proc-buffer-name)))
1248 ;; Always prefer dedicated
1249 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1250 (and global-running global-proc-buffer-name)))))
1252 (defun python-shell-get-or-create-process ()
1253 "Get or create an inferior Python process for current buffer and return it."
1254 (let* ((old-buffer (current-buffer))
1255 (dedicated-proc-name (python-shell-get-process-name t))
1256 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1257 (global-proc-name (python-shell-get-process-name nil))
1258 (global-proc-buffer-name (format "*%s*" global-proc-name))
1259 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1260 (global-running (comint-check-proc global-proc-buffer-name))
1261 (current-prefix-arg 4))
1262 (when (and (not dedicated-running) (not global-running))
1263 (if (call-interactively 'run-python)
1264 (setq dedicated-running t)
1265 (setq global-running t)))
1266 ;; Always prefer dedicated
1267 (switch-to-buffer old-buffer)
1268 (get-buffer-process (if dedicated-running
1269 dedicated-proc-buffer-name
1270 global-proc-buffer-name))))
1272 (defun python-shell-send-string (string &optional process msg)
1273 "Send STRING to inferior Python PROCESS.
1274 When MSG is non-nil messages the first line of STRING."
1275 (interactive "sPython command: ")
1276 (let ((process (or process (python-shell-get-or-create-process)))
1277 (lines (split-string string "\n" t)))
1279 (message (format "Sent: %s..." (nth 0 lines))))
1280 (if (> (length lines) 1)
1281 (let* ((temp-file-name (make-temp-file "py"))
1282 (file-name (or (buffer-file-name) temp-file-name)))
1283 (with-temp-file temp-file-name
1285 (delete-trailing-whitespace))
1286 (python-shell-send-file file-name process temp-file-name))
1287 (comint-send-string process string)
1288 (when (or (not (string-match "\n$" string))
1289 (string-match "\n[ \t].*\n?$" string))
1290 (comint-send-string process "\n")))))
1292 (defun python-shell-send-string-no-output (string &optional process msg)
1293 "Send STRING to PROCESS and inhibit output.
1294 When MSG is non-nil messages the first line of STRING. Return
1296 (let* ((output-buffer)
1297 (process (or process (python-shell-get-or-create-process)))
1298 (comint-preoutput-filter-functions
1299 (append comint-preoutput-filter-functions
1300 '(ansi-color-filter-apply
1302 (setq output-buffer (concat output-buffer string))
1304 (python-shell-send-string string process msg)
1305 (accept-process-output process)
1306 ;; Cleanup output prompt regexp
1307 (when (and (not (string= "" output-buffer))
1308 (> (length python-shell-prompt-output-regexp) 0))
1311 (insert output-buffer)
1312 (goto-char (point-min))
1313 (forward-comment 9999)
1314 (buffer-substring-no-properties
1316 (and (looking-at python-shell-prompt-output-regexp)
1318 python-shell-prompt-output-regexp nil t 1))
1322 (lambda (string) string)
1323 (butlast (split-string output-buffer "\n")) "\n")))
1325 (defun python-shell-send-region (start end)
1326 "Send the region delimited by START and END to inferior Python process."
1328 (let ((deactivate-mark nil))
1329 (python-shell-send-string (buffer-substring start end) nil t)))
1331 (defun python-shell-send-buffer ()
1332 "Send the entire buffer to inferior Python process."
1336 (python-shell-send-region (point-min) (point-max))))
1338 (defun python-shell-send-defun (arg)
1339 "Send the current defun to inferior Python process.
1340 When argument ARG is non-nil sends the innermost defun."
1343 (python-shell-send-region
1345 (or (python-beginning-of-defun-function)
1346 (progn (beginning-of-line) (point-marker))))
1348 (or (python-end-of-defun-function)
1349 (progn (end-of-line) (point-marker)))))))
1351 (defun python-shell-send-file (file-name &optional process temp-file-name)
1352 "Send FILE-NAME to inferior Python PROCESS.
1353 If TEMP-FILE-NAME is passed then that file is used for processing
1354 instead, while internally the shell will continue to use
1356 (interactive "fFile to send: ")
1357 (let* ((process (or process (python-shell-get-or-create-process)))
1358 (temp-file-name (when temp-file-name
1359 (expand-file-name temp-file-name)))
1360 (file-name (or (expand-file-name file-name) temp-file-name)))
1361 (when (not file-name)
1362 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1363 (with-current-buffer (process-buffer process)
1364 (setq inferior-python-mode-current-file
1365 (convert-standard-filename file-name)))
1366 (python-shell-send-string
1368 (concat "__pyfile = open('''%s''');"
1369 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1371 (or temp-file-name file-name) file-name)
1374 (defun python-shell-switch-to-shell ()
1375 "Switch to inferior Python process buffer."
1377 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1379 (defun python-shell-send-setup-code ()
1380 "Send all setup code for shell.
1381 This function takes the list of setup code to send from the
1382 `python-shell-setup-codes' list."
1383 (let ((msg "Sent %s")
1384 (process (get-buffer-process (current-buffer))))
1385 (accept-process-output process python-shell-send-setup-max-wait)
1386 (dolist (code python-shell-setup-codes)
1389 (setq msg (cdr code)))
1390 (message (format msg code))
1391 (python-shell-send-string-no-output
1392 (symbol-value code) process)))))
1394 (add-hook 'inferior-python-mode-hook
1395 #'python-shell-send-setup-code)
1398 ;;; Shell completion
1400 (defvar python-shell-completion-setup-code
1404 def __COMPLETER_all_completions(text): []
1407 readline.set_completer(rlcompleter.Completer().complete)
1408 def __COMPLETER_all_completions(text):
1414 res = readline.get_completer()(text, i)
1417 completions.append(res)
1421 "Code used to setup completion in inferior Python processes.")
1423 (defvar python-shell-completion-string-code
1424 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1425 "Python code used to get a string of completions separated by semicolons.")
1427 (defun python-shell-completion--get-completions (input process)
1428 "Retrieve available completions for INPUT using PROCESS."
1429 (with-current-buffer (process-buffer process)
1430 (let ((completions (python-shell-send-string-no-output
1431 (format python-shell-completion-string-code input)
1433 (when (> (length completions) 2)
1434 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
1436 (defun python-shell-completion--get-completion (input completions)
1437 "Get completion for INPUT using COMPLETIONS."
1438 (let ((completion (when completions
1439 (try-completion input completions))))
1440 (cond ((eq completion t)
1443 (message "Can't find completion for \"%s\"" input)
1446 ((not (string= input completion))
1449 (message "Making completion list...")
1450 (with-output-to-temp-buffer "*Python Completions*"
1451 (display-completion-list
1452 (all-completions input completions)))
1455 (defun python-shell-completion-complete-at-point ()
1456 "Perform completion at point in inferior Python process."
1458 (with-syntax-table python-dotty-syntax-table
1459 (when (and comint-last-prompt-overlay
1460 (> (point-marker) (overlay-end comint-last-prompt-overlay)))
1461 (let* ((process (get-buffer-process (current-buffer)))
1462 (input (substring-no-properties
1463 (or (comint-word (current-word)) "") nil nil)))
1464 (delete-char (- (length input)))
1466 (python-shell-completion--get-completion
1467 input (python-shell-completion--get-completions input process)))))))
1469 (defun python-shell-completion-complete-or-indent ()
1470 "Complete or indent depending on the context.
1471 If content before pointer is all whitespace indent. If not try
1474 (if (string-match "^[[:space:]]*$"
1475 (buffer-substring (comint-line-beginning-position)
1477 (indent-for-tab-command)
1478 (comint-dynamic-complete)))
1481 ;;; PDB Track integration
1483 (defvar python-pdbtrack-stacktrace-info-regexp
1484 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1485 "Regular Expression matching stacktrace information.
1486 Used to extract the current line and module beign inspected. The
1487 regexp should not start with a caret (^) and can contain a string
1488 placeholder (\%s) which is replaced with the filename beign
1489 inspected (so other files in the debugging process are not
1492 (defvar python-pdbtrack-tracking-buffers '()
1493 "Alist containing elements of form (#<buffer> . #<buffer>).
1494 The car of each element of the alist is the tracking buffer and
1495 the cdr is the tracked buffer.")
1497 (defun python-pdbtrack-get-or-add-tracking-buffers ()
1498 "Get/Add a tracked buffer for the current buffer.
1499 Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1500 Returns a cons with the form:
1501 * (#<tracking buffer> . #< tracked buffer>)."
1503 (assq (current-buffer) python-pdbtrack-tracking-buffers)
1504 (let* ((file (with-current-buffer (current-buffer)
1505 inferior-python-mode-current-file))
1507 `(,(current-buffer) .
1508 ,(or (get-file-buffer file)
1509 (find-file-noselect file)))))
1510 (set-buffer (cdr tracking-buffers))
1512 (set-buffer (car tracking-buffers))
1513 (setq python-pdbtrack-tracking-buffers
1514 (cons tracking-buffers python-pdbtrack-tracking-buffers))
1517 (defun python-pdbtrack-comint-output-filter-function (output)
1518 "Move overlay arrow to current pdb line in tracked buffer.
1519 Argument OUTPUT is a string with the output from the comint process."
1520 (when (not (string= output ""))
1521 (let ((full-output (ansi-color-filter-apply
1522 (buffer-substring comint-last-input-end
1524 (if (string-match python-shell-prompt-pdb-regexp full-output)
1525 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1529 (format python-pdbtrack-stacktrace-info-regexp
1531 inferior-python-mode-current-file))
1533 (string-to-number (or (match-string-no-properties 1 full-output) ""))))
1534 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers)))
1535 (tracked-buffer-line-pos))
1537 (with-current-buffer (cdr tracking-buffers)
1538 (set (make-local-variable 'overlay-arrow-string) "=>")
1539 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1540 (setq tracked-buffer-line-pos (progn
1541 (goto-char (point-min))
1542 (forward-line (1- line-num))
1544 (when tracked-buffer-window
1545 (set-window-point tracked-buffer-window tracked-buffer-line-pos))
1546 (set-marker overlay-arrow-position tracked-buffer-line-pos)))
1547 (pop-to-buffer (cdr tracking-buffers))
1548 (switch-to-buffer-other-window (car tracking-buffers)))
1549 (let ((tracking-buffers (assq (current-buffer)
1550 python-pdbtrack-tracking-buffers)))
1551 (when tracking-buffers
1552 (if inferior-python-mode-current-file
1553 (with-current-buffer (cdr tracking-buffers)
1554 (set-marker overlay-arrow-position nil))
1555 (kill-buffer (cdr tracking-buffers)))
1556 (setq python-pdbtrack-tracking-buffers
1557 (assq-delete-all (current-buffer)
1558 python-pdbtrack-tracking-buffers)))))))
1562 ;;; Symbol completion
1564 (defun python-completion-complete-at-point ()
1565 "Complete current symbol at point.
1566 For this to work the best as possible you should call
1567 `python-shell-send-buffer' from time to time so context in
1568 inferior python process is updated properly."
1570 (let ((process (python-shell-get-process)))
1572 (error "Completion needs an inferior Python process running")
1573 (with-syntax-table python-dotty-syntax-table
1574 (let* ((input (substring-no-properties
1575 (or (comint-word (current-word)) "") nil nil))
1576 (completions (python-shell-completion--get-completions
1578 (delete-char (- (length input)))
1580 (python-shell-completion--get-completion
1581 input completions)))))))
1583 (add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.")
1588 (defcustom python-fill-comment-function 'python-fill-comment
1589 "Function to fill comments.
1590 This is the function used by `python-fill-paragraph-function' to
1596 (defcustom python-fill-string-function 'python-fill-string
1597 "Function to fill strings.
1598 This is the function used by `python-fill-paragraph-function' to
1604 (defcustom python-fill-decorator-function 'python-fill-decorator
1605 "Function to fill decorators.
1606 This is the function used by `python-fill-paragraph-function' to
1612 (defcustom python-fill-paren-function 'python-fill-paren
1613 "Function to fill parens.
1614 This is the function used by `python-fill-paragraph-function' to
1620 (defun python-fill-paragraph-function (&optional justify)
1621 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1622 If any of the current line is in or at the end of a multi-line string,
1623 fill the string or the paragraph of it that point is in, preserving
1624 the string's indentation.
1625 Optional argument JUSTIFY defines if the paragraph should be justified."
1628 (back-to-indentation)
1631 ((funcall python-fill-comment-function justify))
1632 ;; Strings/Docstrings
1633 ((save-excursion (skip-chars-forward "\"'uUrR")
1634 (python-info-ppss-context 'string))
1635 (funcall python-fill-string-function justify))
1637 ((equal (char-after (save-excursion
1638 (back-to-indentation)
1639 (point-marker))) ?@)
1640 (funcall python-fill-decorator-function justify))
1642 ((or (python-info-ppss-context 'paren)
1643 (looking-at (python-rx open-paren))
1645 (skip-syntax-forward "^(" (line-end-position))
1646 (looking-at (python-rx open-paren))))
1647 (funcall python-fill-paren-function justify))
1650 (defun python-fill-comment (&optional justify)
1651 "Comment fill function for `python-fill-paragraph-function'.
1652 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1653 (fill-comment-paragraph justify))
1655 (defun python-fill-string (&optional justify)
1656 "String fill function for `python-fill-paragraph-function'.
1657 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1658 (let ((marker (point-marker))
1659 (string-start-marker
1661 (skip-chars-forward "\"'uUrR")
1662 (goto-char (python-info-ppss-context 'string))
1663 (skip-chars-forward "\"'uUrR")
1665 (reg-start (line-beginning-position))
1668 (while (python-info-ppss-context 'string)
1669 (goto-char (1+ (point-marker))))
1670 (skip-chars-backward "\"'")
1672 (reg-end (line-end-position))
1673 (fill-paragraph-function))
1675 (narrow-to-region reg-start reg-end)
1677 (goto-char string-start-marker)
1678 (delete-region (point-marker) (progn
1679 (skip-syntax-forward "> ")
1681 (goto-char string-end-marker)
1682 (delete-region (point-marker) (progn
1683 (skip-syntax-backward "> ")
1687 (fill-paragraph justify))
1688 ;; If there is a newline in the docstring lets put triple
1689 ;; quote in it's own line to follow pep 8
1690 (when (save-excursion
1691 (re-search-backward "\n" string-start-marker t))
1693 (newline-and-indent))
1694 (fill-paragraph justify)))) t)
1696 (defun python-fill-decorator (&optional justify)
1697 "Decorator fill function for `python-fill-paragraph-function'.
1698 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1701 (defun python-fill-paren (&optional justify)
1702 "Paren fill function for `python-fill-paragraph-function'.
1703 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1705 (narrow-to-region (progn
1706 (while (python-info-ppss-context 'paren)
1707 (goto-char (1- (point-marker))))
1709 (line-beginning-position))
1711 (when (not (python-info-ppss-context 'paren))
1713 (when (not (python-info-ppss-context 'paren))
1714 (skip-syntax-backward "^)")))
1715 (while (python-info-ppss-context 'paren)
1716 (goto-char (1+ (point-marker))))
1718 (let ((paragraph-start "\f\\|[ \t]*$")
1719 (paragraph-separate ",")
1720 (fill-paragraph-function))
1721 (goto-char (point-min))
1722 (fill-paragraph justify))
1725 (python-indent-line)
1726 (goto-char (line-end-position)))) t)
1731 (defcustom python-skeleton-autoinsert nil
1732 "Non-nil means template skeletons will be automagically inserted.
1733 This happens when pressing \"if<SPACE>\", for example, to prompt for
1738 (defvar python-skeleton-available '()
1739 "Internal list of available skeletons.")
1740 (make-variable-buffer-local 'inferior-python-mode-current-file)
1742 (define-abbrev-table 'python-mode-abbrev-table ()
1743 "Abbrev table for Python mode."
1745 ;; Allow / inside abbrevs.
1746 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1747 ;; Only expand in code.
1748 :enable-function (lambda ()
1750 (not (or (python-info-ppss-context 'string)
1751 (python-info-ppss-context 'comment)))
1752 python-skeleton-autoinsert)))
1754 (defmacro python-skeleton-define (name doc &rest skel)
1755 "Define a `python-mode' skeleton using NAME DOC and SKEL.
1756 The skeleton will be bound to python-skeleton-NAME and will
1757 be added to `python-mode-abbrev-table'."
1758 (let* ((name (symbol-name name))
1759 (function-name (intern (concat "python-skeleton-" name))))
1761 (define-abbrev python-mode-abbrev-table ,name "" ',function-name)
1762 (setq python-skeleton-available
1763 (cons ',function-name python-skeleton-available))
1764 (define-skeleton ,function-name
1766 (format "Insert %s statement." name))
1768 (put 'python-skeleton-define 'lisp-indent-function 2)
1770 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
1771 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
1772 The skeleton will be bound to python-skeleton-NAME."
1773 (let* ((name (symbol-name name))
1774 (function-name (intern (concat "python-skeleton--" name)))
1776 "Add '%s' clause? " name)))
1779 `(< ,(format "%s:" name) \n \n
1781 `(define-skeleton ,function-name
1783 (format "Auxiliary skeleton for %s statement." name))
1785 (unless (y-or-n-p ,msg)
1788 (put 'python-define-auxiliary-skeleton 'lisp-indent-function 2)
1790 (python-define-auxiliary-skeleton else nil)
1792 (python-define-auxiliary-skeleton except nil)
1794 (python-define-auxiliary-skeleton finally nil)
1796 (python-skeleton-define if nil
1800 ("other condition, %s: "
1804 '(python-skeleton--else) | ^)
1806 (python-skeleton-define while nil
1810 '(python-skeleton--else) | ^)
1812 (python-skeleton-define for nil
1816 '(python-skeleton--else) | ^)
1818 (python-skeleton-define try nil
1824 "except " str ":" \n
1827 '(python-skeleton--except)
1828 '(python-skeleton--else)
1829 '(python-skeleton--finally) | ^)
1831 (python-skeleton-define def nil
1833 "def " str " (" ("Parameter, %s: "
1834 (unless (equal ?\( (char-before)) ", ")
1836 "\"\"\"" - "\"\"\"" \n
1839 (python-skeleton-define class nil
1841 "class " str " (" ("Inheritance, %s: "
1842 (unless (equal ?\( (char-before)) ", ")
1846 "\"\"\"" - "\"\"\"" \n
1849 (defun python-skeleton-add-menu-items ()
1850 "Add menu items to Python->Skeletons menu."
1851 (let ((skeletons (sort python-skeleton-available 'string<))
1853 (dolist (skeleton skeletons)
1855 nil '("Python" "Skeletons")
1857 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
1862 (defvar python-ffap-setup-code
1863 "def __FFAP_get_module_path(module):
1866 path = __import__(module).__file__
1867 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
1872 "Python code to get a module path.")
1874 (defvar python-ffap-string-code
1875 "__FFAP_get_module_path('''%s''')\n"
1876 "Python code used to get a string with the path of a module.")
1878 (defun python-ffap-module-path (module)
1879 "Function for `ffap-alist' to return path for MODULE."
1881 (and (eq major-mode 'inferior-python-mode)
1882 (get-buffer-process (current-buffer)))
1883 (python-shell-get-process))))
1887 (python-shell-send-string-no-output
1888 (format python-ffap-string-code module) process)))
1890 (substring-no-properties module-file 1 -1))))))
1892 (eval-after-load "ffap"
1894 (push '(python-mode . python-ffap-module-path) ffap-alist)
1895 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
1900 (defvar python-check-command
1901 "pychecker --stdlib"
1902 "Command used to check a Python file.")
1904 (defvar python-check-custom-command nil
1907 (defun python-check (command)
1908 "Check a Python file (default current buffer's file).
1909 Runs COMMAND, a shell command, as if by `compile'. See
1910 `python-check-command' for the default."
1912 (list (read-string "Check command: "
1913 (or python-check-custom-command
1914 (concat python-check-command " "
1915 (shell-quote-argument
1917 (let ((name (buffer-file-name)))
1919 (file-name-nondirectory name)))
1921 (setq python-check-custom-command command)
1922 (save-some-buffers (not compilation-ask-about-save) nil)
1923 (compilation-start command))
1928 (defvar python-eldoc-setup-code
1929 "def __PYDOC_get_help(obj):
1932 if hasattr(obj, 'startswith'):
1933 obj = eval(obj, globals())
1934 doc = inspect.getdoc(obj)
1935 if not doc and callable(obj):
1937 if inspect.isclass(obj) and hasattr(obj, '__init__'):
1938 target = obj.__init__
1944 args = inspect.formatargspec(
1945 *inspect.getargspec(target)
1948 doc = '{objtype} {name}{args}'.format(
1949 objtype=objtype, name=name, args=args
1952 doc = doc.splitlines()[0]
1959 "Python code to setup documentation retrieval.")
1961 (defvar python-eldoc-string-code
1962 "__PYDOC_get_help('''%s''')\n"
1963 "Python code used to get a string with the documentation of an object.")
1965 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
1966 "Internal implementation to get documentation at point.
1967 If not FORCE-INPUT is passed then what `current-word' returns
1968 will be used. If not FORCE-PROCESS is passed what
1969 `python-shell-get-process' returns is used."
1970 (let ((process (or force-process (python-shell-get-process))))
1972 "Eldoc needs an inferior Python process running."
1973 (let* ((current-defun (python-info-current-defun))
1974 (input (or force-input
1975 (with-syntax-table python-dotty-syntax-table
1976 (if (not current-defun)
1978 (concat current-defun "." (current-word))))))
1979 (ppss (syntax-ppss))
1980 (help (when (and input
1981 (not (string= input (concat current-defun ".")))
1982 (not (or (python-info-ppss-context 'string ppss)
1983 (python-info-ppss-context 'comment ppss))))
1984 (when (string-match (concat
1985 (regexp-quote (concat current-defun "."))
1989 (goto-char (point-min))
1992 (delete-region (point-marker) (search-forward "self."))
1993 (setq input (buffer-substring (point-min) (point-max)))))
1994 (python-shell-send-string-no-output
1995 (format python-eldoc-string-code input) process))))
1996 (with-current-buffer (process-buffer process)
1997 (when comint-last-prompt-overlay
1998 (delete-region comint-last-input-end
1999 (overlay-start comint-last-prompt-overlay))))
2001 (not (string= help "\n")))
2004 (defun python-eldoc-function ()
2005 "`eldoc-documentation-function' for Python.
2006 For this to work the best as possible you should call
2007 `python-shell-send-buffer' from time to time so context in
2008 inferior python process is updated properly."
2009 (python-eldoc--get-doc-at-point))
2011 (defun python-eldoc-at-point (symbol)
2012 "Get help on SYMBOL using `help'.
2013 Interactively, prompt for symbol."
2015 (let ((symbol (with-syntax-table python-dotty-syntax-table
2017 (enable-recursive-minibuffers t))
2018 (list (read-string (if symbol
2019 (format "Describe symbol (default %s): " symbol)
2020 "Describe symbol: ")
2022 (let ((process (python-shell-get-process)))
2024 (message "Eldoc needs an inferior Python process running.")
2025 (message (python-eldoc--get-doc-at-point symbol process)))))
2030 (defcustom python-imenu-include-defun-type t
2031 "Non-nil make imenu items to include its type."
2036 (defcustom python-imenu-make-tree t
2037 "Non-nil make imenu to build a tree menu.
2038 Set to nil for speed."
2043 (defcustom python-imenu-subtree-root-label "<Jump to %s>"
2044 "Label displayed to navigate to root from a subtree.
2045 It can contain a \"%s\" which will be replaced with the root name."
2050 (defvar python-imenu-index-alist nil
2051 "Calculated index tree for imenu.")
2053 (defun python-imenu-tree-assoc (keylist tree)
2054 "Using KEYLIST traverse TREE."
2056 (python-imenu-tree-assoc (cdr keylist)
2057 (ignore-errors (assoc (car keylist) tree)))
2060 (defun python-imenu-make-element-tree (element-list full-element plain-index)
2061 "Make a tree from plain alist of module names.
2062 ELEMENT-LIST is the defun name splitted by \".\" and FULL-ELEMENT
2063 is the same thing, the difference is that FULL-ELEMENT remains
2064 untouched in all recursive calls.
2065 Argument PLAIN-INDEX is the calculated plain index used to build the tree."
2066 (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist))
2068 (let* ((subelement-point (cdr (assoc
2069 (mapconcat #'identity full-element ".")
2071 (subelement-name (car element-list))
2072 (subelement-position (python-util-position
2073 subelement-name full-element))
2074 (subelement-path (when subelement-position
2077 (- (length full-element)
2078 subelement-position)))))
2079 (let ((path-ref (python-imenu-tree-assoc subelement-path
2080 python-imenu-index-alist)))
2082 (push (cons subelement-name subelement-point)
2083 python-imenu-index-alist)
2084 (when (not (listp (cdr path-ref)))
2085 ;; Modifiy root cdr to be a list
2087 (list (cons (format python-imenu-subtree-root-label
2090 (mapconcat #'identity
2091 subelement-path ".")
2093 (when (not (assoc subelement-name path-ref))
2094 (push (cons subelement-name subelement-point) (cdr path-ref))))))
2095 (python-imenu-make-element-tree (cdr element-list)
2096 full-element plain-index))))
2098 (defun python-imenu-make-tree (index)
2099 "Build the imenu alist tree from plain INDEX.
2101 The idea of this function is that given the alist:
2104 (\"Test.__init__\" . 200)
2105 (\"Test.some_method\" . 300)
2106 (\"Test.some_method.another\" . 400)
2107 (\"Test.something_else\" . 500)
2109 (\"test.reprint\" . 700)
2110 (\"test.reprint\" . 800))
2112 This tree gets built:
2114 '((\"Test\" . ((\"jump to...\" . 100)
2115 (\"__init__\" . 200)
2116 (\"some_method\" . ((\"jump to...\" . 300)
2117 (\"another\" . 400)))
2118 (\"something_else\" . 500)))
2119 (\"test\" . ((\"jump to...\" . 600)
2121 (\"reprint\" . 800))))
2123 Internally it uses `python-imenu-make-element-tree' to create all
2124 branches for each element."
2125 (setq python-imenu-index-alist nil)
2126 (mapc (lambda (element)
2127 (python-imenu-make-element-tree element element index))
2128 (mapcar (lambda (element)
2129 (split-string (car element) "\\." t)) index))
2130 python-imenu-index-alist)
2132 (defun python-imenu-create-index ()
2133 "`imenu-create-index-function' for Python."
2135 (goto-char (point-max))
2136 (while (python-beginning-of-defun-function 1 t)
2137 (let ((defun-dotted-name
2138 (python-info-current-defun python-imenu-include-defun-type)))
2139 (push (cons defun-dotted-name (point)) index)))
2140 (if python-imenu-make-tree
2141 (python-imenu-make-tree index)
2147 (defun python-info-current-defun (&optional include-type)
2148 "Return name of surrounding function with Python compatible dotty syntax.
2149 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2150 This function is compatible to be used as
2151 `add-log-current-defun-function' since it returns nil if point is
2152 not inside a defun."
2159 (goto-char (line-end-position))
2160 (forward-comment -9999)
2161 (setq min-indent (current-indentation))
2162 (while (python-beginning-of-defun-function 1 t)
2163 (when (or (< (current-indentation) min-indent)
2165 (setq first-run nil)
2166 (setq min-indent (current-indentation))
2167 (looking-at python-nav-beginning-of-defun-regexp)
2169 (if (not include-type)
2170 (match-string-no-properties 1)
2171 (mapconcat 'identity
2173 (match-string-no-properties 0)) " "))
2176 (mapconcat (lambda (string) string) names "."))))
2178 (defun python-info-closing-block ()
2179 "Return the point of the block the current line closes."
2180 (let ((closing-word (save-excursion
2181 (back-to-indentation)
2183 (indentation (current-indentation)))
2184 (when (member closing-word python-indent-dedenters)
2187 (while (and (> (current-indentation) indentation)
2189 (not (back-to-indentation))
2191 (back-to-indentation)
2193 ((not (equal indentation (current-indentation))) nil)
2194 ((string= closing-word "elif")
2195 (when (member (current-word) '("if" "elif"))
2197 ((string= closing-word "else")
2198 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2200 ((string= closing-word "except")
2201 (when (member (current-word) '("try"))
2203 ((string= closing-word "finally")
2204 (when (member (current-word) '("except" "else"))
2205 (point-marker))))))))
2207 (defun python-info-line-ends-backslash-p ()
2208 "Return non-nil if current line ends with backslash."
2209 (string= (or (ignore-errors
2212 (- (line-end-position) 1))) "") "\\"))
2214 (defun python-info-continuation-line-p ()
2215 "Return non-nil if current line is continuation of another."
2216 (or (python-info-line-ends-backslash-p)
2217 (string-match ",[[:space:]]*$" (buffer-substring
2218 (line-beginning-position)
2219 (line-end-position)))
2221 (let ((innermost-paren (progn
2222 (goto-char (line-end-position))
2223 (python-info-ppss-context 'paren))))
2224 (when (and innermost-paren
2225 (and (<= (line-beginning-position) innermost-paren)
2226 (>= (line-end-position) innermost-paren)))
2227 (goto-char innermost-paren)
2228 (looking-at (python-rx open-paren (* space) line-end)))))
2230 (back-to-indentation)
2231 (python-info-ppss-context 'paren))))
2233 (defun python-info-block-continuation-line-p ()
2234 "Return non-nil if current line is a continuation of a block."
2236 (while (and (not (bobp))
2237 (python-info-continuation-line-p))
2240 (back-to-indentation)
2241 (when (looking-at (python-rx block-start))
2244 (defun python-info-assignment-continuation-line-p ()
2245 "Return non-nil if current line is a continuation of an assignment."
2247 (while (and (not (bobp))
2248 (python-info-continuation-line-p))
2251 (back-to-indentation)
2252 (when (and (not (looking-at (python-rx block-start)))
2254 (and (re-search-forward (python-rx not-simple-operator
2256 not-simple-operator)
2257 (line-end-position) t)
2258 (not (or (python-info-ppss-context 'string)
2259 (python-info-ppss-context 'paren)
2260 (python-info-ppss-context 'comment))))))
2263 (defun python-info-ppss-context (type &optional syntax-ppss)
2264 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2265 TYPE can be 'comment, 'string or 'parent. It returns the start
2266 character address of the specified TYPE."
2267 (let ((ppss (or syntax-ppss (syntax-ppss))))
2279 ;;; Utility functions
2282 (defun python-util-merge (type list1 list2 pred)
2283 "Destructively merge lists to produce a new one.
2284 Argument TYPE is for compatibility and ignored. LIST1 and LIST2
2285 are the list to be merged. Ordering of the elements is preserved
2286 according to PRED, a `less-than' predicate on the elements."
2288 (while (and list1 list2)
2289 (if (funcall pred (car list2) (car list1))
2290 (push (pop list2) res)
2291 (push (pop list1) res)))
2292 (nconc (nreverse res) list1 list2)))
2294 (defun python-util-position (item seq)
2295 "Find the first occurrence of ITEM in SEQ.
2296 Return the index of the matching item, or nil if not found."
2297 (let ((member-result (member item seq)))
2299 (- (length seq) (length member-result)))))
2303 (define-derived-mode python-mode fundamental-mode "Python"
2304 "Major mode for editing Python files.
2307 Entry to this mode calls the value of `python-mode-hook'
2308 if that value is non-nil."
2309 (set (make-local-variable 'tab-width) 8)
2310 (set (make-local-variable 'indent-tabs-mode) nil)
2312 (set (make-local-variable 'comment-start) "# ")
2313 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2315 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2316 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2318 (set (make-local-variable 'font-lock-defaults)
2319 '(python-font-lock-keywords
2321 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords)))
2323 (set (make-local-variable 'indent-line-function) #'python-indent-line-function)
2324 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2326 (set (make-local-variable 'paragraph-start) "\\s-*$")
2327 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function)
2329 (set (make-local-variable 'beginning-of-defun-function)
2330 #'python-beginning-of-defun-function)
2331 (set (make-local-variable 'end-of-defun-function)
2332 #'python-end-of-defun-function)
2334 (add-hook 'completion-at-point-functions
2335 'python-completion-complete-at-point nil 'local)
2337 (setq imenu-create-index-function #'python-imenu-create-index)
2339 (set (make-local-variable 'add-log-current-defun-function)
2340 #'python-info-current-defun)
2342 (set (make-local-variable 'skeleton-further-elements)
2344 (< '(backward-delete-char-untabify (min python-indent-offset
2346 (^ '(- (1+ (current-indentation))))))
2348 (set (make-local-variable 'eldoc-documentation-function)
2349 #'python-eldoc-function)
2351 (add-to-list 'hs-special-modes-alist
2352 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2354 (python-end-of-defun-function)) nil))
2356 (set (make-local-variable 'mode-require-final-newline) t)
2358 (set (make-local-variable 'outline-regexp)
2359 (python-rx (* space) block-start))
2360 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2361 (set (make-local-variable 'outline-level)
2363 "`outline-level' function for Python mode."
2364 (1+ (/ (current-indentation) python-indent-offset))))
2366 (python-skeleton-add-menu-items)
2368 (when python-indent-guess-indent-offset
2369 (python-indent-guess-indent-offset)))
2373 ;;; python.el ends here