diff options
| author | Bill Wohler | 2012-11-24 19:43:02 -0800 |
|---|---|---|
| committer | Bill Wohler | 2012-11-24 19:43:02 -0800 |
| commit | 5244bc019bf7376caff3bb198ff674e0ad9fb0e6 (patch) | |
| tree | 02ee1615e904771f692ec2957c79a08ae029a13d /lisp/progmodes/python.el | |
| parent | 9f7e719509474e92f85955e22e57ffeebd4e96f3 (diff) | |
| parent | c07a6ded1df2f4156badc9add2953579622c3722 (diff) | |
| download | emacs-5244bc019bf7376caff3bb198ff674e0ad9fb0e6.tar.gz emacs-5244bc019bf7376caff3bb198ff674e0ad9fb0e6.zip | |
Merge from trunk.
Diffstat (limited to 'lisp/progmodes/python.el')
| -rw-r--r-- | lisp/progmodes/python.el | 5607 |
1 files changed, 3074 insertions, 2533 deletions
diff --git a/lisp/progmodes/python.el b/lisp/progmodes/python.el index 6081d8e838b..550c5f5a129 100644 --- a/lisp/progmodes/python.el +++ b/lisp/progmodes/python.el | |||
| @@ -1,342 +1,578 @@ | |||
| 1 | ;;; python.el --- silly walks for Python -*- coding: iso-8859-1 -*- | 1 | ;;; python.el --- Python's flying circus support for Emacs |
| 2 | 2 | ||
| 3 | ;; Copyright (C) 2003-2011 Free Software Foundation, Inc. | 3 | ;; Copyright (C) 2003-2012 Free Software Foundation, Inc. |
| 4 | 4 | ||
| 5 | ;; Author: Dave Love <fx@gnu.org> | 5 | ;; Author: Fabián E. Gallina <fabian@anue.biz> |
| 6 | ;; URL: https://github.com/fgallina/python.el | ||
| 7 | ;; Version: 0.24.2 | ||
| 6 | ;; Maintainer: FSF | 8 | ;; Maintainer: FSF |
| 7 | ;; Created: Nov 2003 | 9 | ;; Created: Jul 2010 |
| 8 | ;; Keywords: languages | 10 | ;; Keywords: languages |
| 9 | 11 | ||
| 10 | ;; This file is part of GNU Emacs. | 12 | ;; This file is part of GNU Emacs. |
| 11 | 13 | ||
| 12 | ;; GNU Emacs is free software: you can redistribute it and/or modify | 14 | ;; GNU Emacs is free software: you can redistribute it and/or modify |
| 13 | ;; it under the terms of the GNU General Public License as published by | 15 | ;; it under the terms of the GNU General Public License as published |
| 14 | ;; the Free Software Foundation, either version 3 of the License, or | 16 | ;; by the Free Software Foundation, either version 3 of the License, |
| 15 | ;; (at your option) any later version. | 17 | ;; or (at your option) any later version. |
| 16 | 18 | ||
| 17 | ;; GNU Emacs is distributed in the hope that it will be useful, | 19 | ;; GNU Emacs is distributed in the hope that it will be useful, but |
| 18 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of | 20 | ;; WITHOUT ANY WARRANTY; without even the implied warranty of |
| 19 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | 21 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 20 | ;; GNU General Public License for more details. | 22 | ;; General Public License for more details. |
| 21 | 23 | ||
| 22 | ;; You should have received a copy of the GNU General Public License | 24 | ;; You should have received a copy of the GNU General Public License |
| 23 | ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. | 25 | ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. |
| 24 | 26 | ||
| 25 | ;;; Commentary: | 27 | ;;; Commentary: |
| 26 | 28 | ||
| 27 | ;; Major mode for editing Python, with support for inferior processes. | 29 | ;; Major mode for editing Python files with some fontification and |
| 28 | 30 | ;; indentation bits extracted from original Dave Love's python.el | |
| 29 | ;; There is another Python mode, python-mode.el: | 31 | ;; found in GNU/Emacs. |
| 30 | ;; http://launchpad.net/python-mode | 32 | |
| 31 | ;; used by XEmacs, and originally maintained with Python. | 33 | ;; Implements Syntax highlighting, Indentation, Movement, Shell |
| 32 | ;; That isn't covered by an FSF copyright assignment (?), unlike this | 34 | ;; interaction, Shell completion, Shell virtualenv support, Pdb |
| 33 | ;; code, and seems not to be well-maintained for Emacs (though I've | 35 | ;; tracking, Symbol completion, Skeletons, FFAP, Code Check, Eldoc, |
| 34 | ;; submitted fixes). This mode is rather simpler and is better in | 36 | ;; imenu. |
| 35 | ;; other ways. In particular, using the syntax functions with text | 37 | |
| 36 | ;; properties maintained by font-lock makes it more correct with | 38 | ;; Syntax highlighting: Fontification of code is provided and supports |
| 37 | ;; arbitrary string and comment contents. | 39 | ;; python's triple quoted strings properly. |
| 38 | 40 | ||
| 39 | ;; This doesn't implement all the facilities of python-mode.el. Some | 41 | ;; Indentation: Automatic indentation with indentation cycling is |
| 40 | ;; just need doing, e.g. catching exceptions in the inferior Python | 42 | ;; provided, it allows you to navigate different available levels of |
| 41 | ;; buffer (but see M-x pdb for debugging). [Actually, the use of | 43 | ;; indentation by hitting <tab> several times. Also when inserting a |
| 42 | ;; `compilation-shell-minor-mode' now is probably enough for that.] | 44 | ;; colon the `python-indent-electric-colon' command is invoked and |
| 43 | ;; Others don't seem appropriate. For instance, | 45 | ;; causes the current line to be dedented automatically if needed. |
| 44 | ;; `forward-into-nomenclature' should be done separately, since it's | 46 | |
| 45 | ;; not specific to Python, and I've installed a minor mode to do the | 47 | ;; Movement: `beginning-of-defun' and `end-of-defun' functions are |
| 46 | ;; job properly in Emacs 23. [CC mode 5.31 contains an incompatible | 48 | ;; properly implemented. There are also specialized |
| 47 | ;; feature, `subword-mode' which is intended to have a similar | 49 | ;; `forward-sentence' and `backward-sentence' replacements called |
| 48 | ;; effect, but actually only affects word-oriented keybindings.] | 50 | ;; `python-nav-forward-block', `python-nav-backward-block' |
| 49 | 51 | ;; respectively which navigate between beginning of blocks of code. | |
| 50 | ;; Other things seem more natural or canonical here, e.g. the | 52 | ;; Extra functions `python-nav-forward-statement', |
| 51 | ;; {beginning,end}-of-defun implementation dealing with nested | 53 | ;; `python-nav-backward-statement', |
| 52 | ;; definitions, and the inferior mode following `cmuscheme'. (The | 54 | ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement', |
| 53 | ;; inferior mode can find the source of errors from | 55 | ;; `python-nav-beginning-of-block' and `python-nav-end-of-block' are |
| 54 | ;; `python-send-region' & al via `compilation-shell-minor-mode'.) | 56 | ;; included but no bound to any key. At last but not least the |
| 55 | ;; There is (limited) symbol completion using lookup in Python and | 57 | ;; specialized `python-nav-forward-sexp' allows easy |
| 56 | ;; Eldoc support also using the inferior process. Successive TABs | 58 | ;; navigation between code blocks. |
| 57 | ;; cycle between possible indentations for the line. | 59 | |
| 58 | 60 | ;; Shell interaction: is provided and allows you to execute easily any | |
| 59 | ;; Even where it has similar facilities, this mode is incompatible | 61 | ;; block of code of your current buffer in an inferior Python process. |
| 60 | ;; with python-mode.el in some respects. For instance, various key | 62 | |
| 61 | ;; bindings are changed to obey Emacs conventions. | 63 | ;; Shell completion: hitting tab will try to complete the current |
| 62 | 64 | ;; word. Shell completion is implemented in a manner that if you | |
| 63 | ;; TODO: See various Fixmes below. | 65 | ;; change the `python-shell-interpreter' to any other (for example |
| 64 | 66 | ;; IPython) it should be easy to integrate another way to calculate | |
| 65 | ;; Fixme: This doesn't support (the nascent) Python 3 . | 67 | ;; completions. You just need to specify your custom |
| 68 | ;; `python-shell-completion-setup-code' and | ||
| 69 | ;; `python-shell-completion-string-code'. | ||
| 70 | |||
| 71 | ;; Here is a complete example of the settings you would use for | ||
| 72 | ;; iPython 0.11: | ||
| 73 | |||
| 74 | ;; (setq | ||
| 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") | ||
| 85 | |||
| 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': | ||
| 89 | |||
| 90 | ;; (setq python-shell-completion-string-code | ||
| 91 | ;; "';'.join(__IP.complete('''%s'''))\n" | ||
| 92 | ;; python-shell-completion-module-string-code "") | ||
| 93 | |||
| 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: | ||
| 97 | |||
| 98 | ;; (setq | ||
| 99 | ;; python-shell-interpreter "C:\\Python27\\python.exe" | ||
| 100 | ;; python-shell-interpreter-args | ||
| 101 | ;; "-i C:\\Python27\\Scripts\\ipython-script.py") | ||
| 102 | |||
| 103 | ;; That will spawn the iPython process correctly (Of course you need | ||
| 104 | ;; to modify the paths according to your system). | ||
| 105 | |||
| 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. | ||
| 111 | |||
| 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/ | ||
| 119 | ;; virtualenv: | ||
| 120 | |||
| 121 | ;; (setq python-shell-process-environment | ||
| 122 | ;; (list | ||
| 123 | ;; (format "PATH=%s" (mapconcat | ||
| 124 | ;; 'identity | ||
| 125 | ;; (reverse | ||
| 126 | ;; (cons (getenv "PATH") | ||
| 127 | ;; '("/path/to/env/bin/"))) | ||
| 128 | ;; ":")) | ||
| 129 | ;; "VIRTUAL_ENV=/path/to/env/")) | ||
| 130 | ;; (python-shell-exec-path . ("/path/to/env/bin/")) | ||
| 131 | |||
| 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: | ||
| 138 | |||
| 139 | ;; (setq python-shell-virtualenv-path "/path/to/env/") | ||
| 140 | |||
| 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. | ||
| 144 | |||
| 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. | ||
| 148 | |||
| 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. | ||
| 152 | |||
| 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. | ||
| 159 | |||
| 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 | ||
| 162 | ;; running. | ||
| 163 | |||
| 164 | ;; Code check: Check the current file for errors with `python-check' | ||
| 165 | ;; using the program defined in `python-check-command'. | ||
| 166 | |||
| 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. | ||
| 171 | |||
| 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'. | ||
| 176 | |||
| 177 | ;; If you used python-mode.el you probably will miss auto-indentation | ||
| 178 | ;; when inserting newlines. To achieve the same behavior you have | ||
| 179 | ;; two options: | ||
| 180 | |||
| 181 | ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j. | ||
| 182 | |||
| 183 | ;; 2) Add the following hook in your .emacs: | ||
| 184 | |||
| 185 | ;; (add-hook 'python-mode-hook | ||
| 186 | ;; #'(lambda () | ||
| 187 | ;; (define-key python-mode-map "\C-m" 'newline-and-indent))) | ||
| 188 | |||
| 189 | ;; I'd recommend the first one since you'll get the same behavior for | ||
| 190 | ;; all modes out-of-the-box. | ||
| 191 | |||
| 192 | ;;; Installation: | ||
| 193 | |||
| 194 | ;; Add this to your .emacs: | ||
| 195 | |||
| 196 | ;; (add-to-list 'load-path "/folder/containing/file") | ||
| 197 | ;; (require 'python) | ||
| 198 | |||
| 199 | ;;; TODO: | ||
| 66 | 200 | ||
| 67 | ;;; Code: | 201 | ;;; Code: |
| 68 | 202 | ||
| 203 | (require 'ansi-color) | ||
| 69 | (require 'comint) | 204 | (require 'comint) |
| 205 | (eval-when-compile (require 'cl-lib)) | ||
| 70 | 206 | ||
| 71 | (eval-when-compile | 207 | ;; Avoid compiler warnings |
| 72 | (require 'compile) | 208 | (defvar view-return-to-alist) |
| 73 | (require 'hippie-exp)) | 209 | (defvar compilation-error-regexp-alist) |
| 210 | (defvar outline-heading-end-regexp) | ||
| 74 | 211 | ||
| 75 | (autoload 'comint-mode "comint") | 212 | (autoload 'comint-mode "comint") |
| 76 | 213 | ||
| 214 | ;;;###autoload | ||
| 215 | (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode)) | ||
| 216 | ;;;###autoload | ||
| 217 | (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode)) | ||
| 218 | |||
| 77 | (defgroup python nil | 219 | (defgroup python nil |
| 78 | "Silly walks in the Python language." | 220 | "Python Language's flying circus support for Emacs." |
| 79 | :group 'languages | 221 | :group 'languages |
| 80 | :version "22.1" | 222 | :version "23.2" |
| 81 | :link '(emacs-commentary-link "python")) | 223 | :link '(emacs-commentary-link "python")) |
| 224 | |||
| 82 | 225 | ||
| 83 | ;;;###autoload | 226 | ;;; Bindings |
| 84 | (add-to-list 'interpreter-mode-alist (cons (purecopy "jython") 'jython-mode)) | 227 | |
| 85 | ;;;###autoload | 228 | (defvar python-mode-map |
| 86 | (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode)) | 229 | (let ((map (make-sparse-keymap))) |
| 87 | ;;;###autoload | 230 | ;; Movement |
| 88 | (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode)) | 231 | (define-key map [remap backward-sentence] 'python-nav-backward-block) |
| 232 | (define-key map [remap forward-sentence] 'python-nav-forward-block) | ||
| 233 | (define-key map [remap backward-up-list] 'python-nav-backward-up-list) | ||
| 234 | (define-key map "\C-c\C-j" 'imenu) | ||
| 235 | ;; Indent specific | ||
| 236 | (define-key map "\177" 'python-indent-dedent-line-backspace) | ||
| 237 | (define-key map (kbd "<backtab>") 'python-indent-dedent-line) | ||
| 238 | (define-key map "\C-c<" 'python-indent-shift-left) | ||
| 239 | (define-key map "\C-c>" 'python-indent-shift-right) | ||
| 240 | (define-key map ":" 'python-indent-electric-colon) | ||
| 241 | ;; Skeletons | ||
| 242 | (define-key map "\C-c\C-tc" 'python-skeleton-class) | ||
| 243 | (define-key map "\C-c\C-td" 'python-skeleton-def) | ||
| 244 | (define-key map "\C-c\C-tf" 'python-skeleton-for) | ||
| 245 | (define-key map "\C-c\C-ti" 'python-skeleton-if) | ||
| 246 | (define-key map "\C-c\C-tt" 'python-skeleton-try) | ||
| 247 | (define-key map "\C-c\C-tw" 'python-skeleton-while) | ||
| 248 | ;; Shell interaction | ||
| 249 | (define-key map "\C-c\C-p" 'run-python) | ||
| 250 | (define-key map "\C-c\C-s" 'python-shell-send-string) | ||
| 251 | (define-key map "\C-c\C-r" 'python-shell-send-region) | ||
| 252 | (define-key map "\C-\M-x" 'python-shell-send-defun) | ||
| 253 | (define-key map "\C-c\C-c" 'python-shell-send-buffer) | ||
| 254 | (define-key map "\C-c\C-l" 'python-shell-send-file) | ||
| 255 | (define-key map "\C-c\C-z" 'python-shell-switch-to-shell) | ||
| 256 | ;; Some util commands | ||
| 257 | (define-key map "\C-c\C-v" 'python-check) | ||
| 258 | (define-key map "\C-c\C-f" 'python-eldoc-at-point) | ||
| 259 | ;; Utilities | ||
| 260 | (substitute-key-definition 'complete-symbol 'completion-at-point | ||
| 261 | map global-map) | ||
| 262 | (easy-menu-define python-menu map "Python Mode menu" | ||
| 263 | `("Python" | ||
| 264 | :help "Python-specific Features" | ||
| 265 | ["Shift region left" python-indent-shift-left :active mark-active | ||
| 266 | :help "Shift region left by a single indentation step"] | ||
| 267 | ["Shift region right" python-indent-shift-right :active mark-active | ||
| 268 | :help "Shift region right by a single indentation step"] | ||
| 269 | "-" | ||
| 270 | ["Start of def/class" beginning-of-defun | ||
| 271 | :help "Go to start of outermost definition around point"] | ||
| 272 | ["End of def/class" end-of-defun | ||
| 273 | :help "Go to end of definition around point"] | ||
| 274 | ["Mark def/class" mark-defun | ||
| 275 | :help "Mark outermost definition around point"] | ||
| 276 | ["Jump to def/class" imenu | ||
| 277 | :help "Jump to a class or function definition"] | ||
| 278 | "--" | ||
| 279 | ("Skeletons") | ||
| 280 | "---" | ||
| 281 | ["Start interpreter" run-python | ||
| 282 | :help "Run inferior Python process in a separate buffer"] | ||
| 283 | ["Switch to shell" python-shell-switch-to-shell | ||
| 284 | :help "Switch to running inferior Python process"] | ||
| 285 | ["Eval string" python-shell-send-string | ||
| 286 | :help "Eval string in inferior Python session"] | ||
| 287 | ["Eval buffer" python-shell-send-buffer | ||
| 288 | :help "Eval buffer in inferior Python session"] | ||
| 289 | ["Eval region" python-shell-send-region | ||
| 290 | :help "Eval region in inferior Python session"] | ||
| 291 | ["Eval defun" python-shell-send-defun | ||
| 292 | :help "Eval defun in inferior Python session"] | ||
| 293 | ["Eval file" python-shell-send-file | ||
| 294 | :help "Eval file in inferior Python session"] | ||
| 295 | ["Debugger" pdb :help "Run pdb under GUD"] | ||
| 296 | "----" | ||
| 297 | ["Check file" python-check | ||
| 298 | :help "Check file for errors"] | ||
| 299 | ["Help on symbol" python-eldoc-at-point | ||
| 300 | :help "Get help on symbol at point"] | ||
| 301 | ["Complete symbol" completion-at-point | ||
| 302 | :help "Complete symbol before point"])) | ||
| 303 | map) | ||
| 304 | "Keymap for `python-mode'.") | ||
| 305 | |||
| 306 | |||
| 307 | ;;; Python specialized rx | ||
| 308 | |||
| 309 | (eval-when-compile | ||
| 310 | (defconst python-rx-constituents | ||
| 311 | `((block-start . ,(rx symbol-start | ||
| 312 | (or "def" "class" "if" "elif" "else" "try" | ||
| 313 | "except" "finally" "for" "while" "with") | ||
| 314 | symbol-end)) | ||
| 315 | (decorator . ,(rx line-start (* space) ?@ (any letter ?_) | ||
| 316 | (* (any word ?_)))) | ||
| 317 | (defun . ,(rx symbol-start (or "def" "class") symbol-end)) | ||
| 318 | (if-name-main . ,(rx line-start "if" (+ space) "__name__" | ||
| 319 | (+ space) "==" (+ space) | ||
| 320 | (any ?' ?\") "__main__" (any ?' ?\") | ||
| 321 | (* space) ?:)) | ||
| 322 | (symbol-name . ,(rx (any letter ?_) (* (any word ?_)))) | ||
| 323 | (open-paren . ,(rx (or "{" "[" "("))) | ||
| 324 | (close-paren . ,(rx (or "}" "]" ")"))) | ||
| 325 | (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))) | ||
| 326 | ;; FIXME: rx should support (not simple-operator). | ||
| 327 | (not-simple-operator . ,(rx | ||
| 328 | (not | ||
| 329 | (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))) | ||
| 330 | ;; FIXME: Use regexp-opt. | ||
| 331 | (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">" | ||
| 332 | "=" "%" "**" "//" "<<" ">>" "<=" "!=" | ||
| 333 | "==" ">=" "is" "not"))) | ||
| 334 | ;; FIXME: Use regexp-opt. | ||
| 335 | (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**=" | ||
| 336 | ">>=" "<<=" "&=" "^=" "|="))) | ||
| 337 | (string-delimiter . ,(rx (and | ||
| 338 | ;; Match even number of backslashes. | ||
| 339 | (or (not (any ?\\ ?\' ?\")) point | ||
| 340 | ;; Quotes might be preceded by a escaped quote. | ||
| 341 | (and (or (not (any ?\\)) point) ?\\ | ||
| 342 | (* ?\\ ?\\) (any ?\' ?\"))) | ||
| 343 | (* ?\\ ?\\) | ||
| 344 | ;; Match single or triple quotes of any kind. | ||
| 345 | (group (or "\"" "\"\"\"" "'" "'''")))))) | ||
| 346 | "Additional Python specific sexps for `python-rx'") | ||
| 347 | |||
| 348 | (defmacro python-rx (&rest regexps) | ||
| 349 | "Python mode specialized rx macro. | ||
| 350 | This variant of `rx' supports common python named REGEXPS." | ||
| 351 | (let ((rx-constituents (append python-rx-constituents rx-constituents))) | ||
| 352 | (cond ((null regexps) | ||
| 353 | (error "No regexp")) | ||
| 354 | ((cdr regexps) | ||
| 355 | (rx-to-string `(and ,@regexps) t)) | ||
| 356 | (t | ||
| 357 | (rx-to-string (car regexps) t)))))) | ||
| 358 | |||
| 89 | 359 | ||
| 90 | ;;;; Font lock | 360 | ;;; Font-lock and syntax |
| 361 | |||
| 362 | (defun python-syntax-context (type &optional syntax-ppss) | ||
| 363 | "Return non-nil if point is on TYPE using SYNTAX-PPSS. | ||
| 364 | TYPE can be `comment', `string' or `paren'. It returns the start | ||
| 365 | character address of the specified TYPE." | ||
| 366 | (declare (compiler-macro | ||
| 367 | (lambda (form) | ||
| 368 | (pcase type | ||
| 369 | (`'comment | ||
| 370 | `(let ((ppss (or ,syntax-ppss (syntax-ppss)))) | ||
| 371 | (and (nth 4 ppss) (nth 8 ppss)))) | ||
| 372 | (`'string | ||
| 373 | `(let ((ppss (or ,syntax-ppss (syntax-ppss)))) | ||
| 374 | (and (nth 3 ppss) (nth 8 ppss)))) | ||
| 375 | (`'paren | ||
| 376 | `(nth 1 (or ,syntax-ppss (syntax-ppss)))) | ||
| 377 | (_ form))))) | ||
| 378 | (let ((ppss (or syntax-ppss (syntax-ppss)))) | ||
| 379 | (pcase type | ||
| 380 | (`comment (and (nth 4 ppss) (nth 8 ppss))) | ||
| 381 | (`string (and (nth 3 ppss) (nth 8 ppss))) | ||
| 382 | (`paren (nth 1 ppss)) | ||
| 383 | (_ nil)))) | ||
| 384 | |||
| 385 | (defun python-syntax-context-type (&optional syntax-ppss) | ||
| 386 | "Return the context type using SYNTAX-PPSS. | ||
| 387 | The type returned can be `comment', `string' or `paren'." | ||
| 388 | (let ((ppss (or syntax-ppss (syntax-ppss)))) | ||
| 389 | (cond | ||
| 390 | ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string)) | ||
| 391 | ((nth 1 ppss) 'paren)))) | ||
| 392 | |||
| 393 | (defsubst python-syntax-comment-or-string-p () | ||
| 394 | "Return non-nil if point is inside 'comment or 'string." | ||
| 395 | (nth 8 (syntax-ppss))) | ||
| 396 | |||
| 397 | (define-obsolete-function-alias | ||
| 398 | 'python-info-ppss-context #'python-syntax-context "24.3") | ||
| 399 | |||
| 400 | (define-obsolete-function-alias | ||
| 401 | 'python-info-ppss-context-type #'python-syntax-context-type "24.3") | ||
| 402 | |||
| 403 | (define-obsolete-function-alias | ||
| 404 | 'python-info-ppss-comment-or-string-p | ||
| 405 | #'python-syntax-comment-or-string-p "24.3") | ||
| 91 | 406 | ||
| 92 | (defvar python-font-lock-keywords | 407 | (defvar python-font-lock-keywords |
| 408 | ;; Keywords | ||
| 93 | `(,(rx symbol-start | 409 | `(,(rx symbol-start |
| 94 | ;; From v 2.7 reference, § keywords. | 410 | (or |
| 95 | ;; def and class dealt with separately below | 411 | "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with" |
| 96 | (or "and" "as" "assert" "break" "continue" "del" "elif" "else" | 412 | "assert" "else" "if" "pass" "yield" "break" "except" "import" "class" |
| 97 | "except" "exec" "finally" "for" "from" "global" "if" | 413 | "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda" |
| 98 | "import" "in" "is" "lambda" "not" "or" "pass" "print" | 414 | "try" |
| 99 | "raise" "return" "try" "while" "with" "yield" | 415 | ;; Python 2: |
| 100 | ;; Not real keywords, but close enough to be fontified as such | 416 | "print" "exec" |
| 101 | "self" "True" "False" | 417 | ;; Python 3: |
| 102 | ;; Python 3 | 418 | ;; False, None, and True are listed as keywords on the Python 3 |
| 103 | "nonlocal") | 419 | ;; documentation, but since they also qualify as constants they are |
| 104 | symbol-end) | 420 | ;; fontified like that in order to keep font-lock consistent between |
| 105 | (,(rx symbol-start "None" symbol-end) ; see § Keywords in 2.7 manual | 421 | ;; Python versions. |
| 106 | . font-lock-constant-face) | 422 | "nonlocal" |
| 107 | ;; Definitions | 423 | ;; Extra: |
| 108 | (,(rx symbol-start (group "class") (1+ space) (group (1+ (or word ?_)))) | 424 | "self") |
| 109 | (1 font-lock-keyword-face) (2 font-lock-type-face)) | 425 | symbol-end) |
| 110 | (,(rx symbol-start (group "def") (1+ space) (group (1+ (or word ?_)))) | 426 | ;; functions |
| 111 | (1 font-lock-keyword-face) (2 font-lock-function-name-face)) | 427 | (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_)))) |
| 112 | ;; Top-level assignments are worth highlighting. | 428 | (1 font-lock-function-name-face)) |
| 113 | (,(rx line-start (group (1+ (or word ?_))) (0+ space) | 429 | ;; classes |
| 114 | (opt (or "+" "-" "*" "**" "/" "//" "&" "%" "|" "^" "<<" ">>")) "=") | 430 | (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_)))) |
| 115 | (1 font-lock-variable-name-face)) | 431 | (1 font-lock-type-face)) |
| 432 | ;; Constants | ||
| 433 | (,(rx symbol-start | ||
| 434 | (or | ||
| 435 | "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__" | ||
| 436 | ;; copyright, license, credits, quit and exit are added by the site | ||
| 437 | ;; module and they are not intended to be used in programs | ||
| 438 | "copyright" "credits" "exit" "license" "quit") | ||
| 439 | symbol-end) . font-lock-constant-face) | ||
| 116 | ;; Decorators. | 440 | ;; Decorators. |
| 117 | (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_)) | 441 | (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_)) |
| 118 | (0+ "." (1+ (or word ?_))))) | 442 | (0+ "." (1+ (or word ?_))))) |
| 119 | (1 font-lock-type-face)) | 443 | (1 font-lock-type-face)) |
| 120 | ;; Built-ins. (The next three blocks are from | 444 | ;; Builtin Exceptions |
| 121 | ;; `__builtin__.__dict__.keys()' in Python 2.7) These patterns | 445 | (,(rx symbol-start |
| 122 | ;; are debatable, but they at least help to spot possible | 446 | (or |
| 123 | ;; shadowing of builtins. | 447 | "ArithmeticError" "AssertionError" "AttributeError" "BaseException" |
| 124 | (,(rx symbol-start (or | 448 | "DeprecationWarning" "EOFError" "EnvironmentError" "Exception" |
| 125 | ;; exceptions | 449 | "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError" |
| 126 | "ArithmeticError" "AssertionError" "AttributeError" | 450 | "ImportError" "ImportWarning" "IndexError" "KeyError" |
| 127 | "BaseException" "DeprecationWarning" "EOFError" | 451 | "KeyboardInterrupt" "LookupError" "MemoryError" "NameError" |
| 128 | "EnvironmentError" "Exception" "FloatingPointError" | 452 | "NotImplementedError" "OSError" "OverflowError" |
| 129 | "FutureWarning" "GeneratorExit" "IOError" "ImportError" | 453 | "PendingDeprecationWarning" "ReferenceError" "RuntimeError" |
| 130 | "ImportWarning" "IndentationError" "IndexError" "KeyError" | 454 | "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning" |
| 131 | "KeyboardInterrupt" "LookupError" "MemoryError" "NameError" | 455 | "SystemError" "SystemExit" "TypeError" "UnboundLocalError" |
| 132 | "NotImplemented" "NotImplementedError" "OSError" | 456 | "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError" |
| 133 | "OverflowError" "PendingDeprecationWarning" "ReferenceError" | 457 | "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError" |
| 134 | "RuntimeError" "RuntimeWarning" "StandardError" | 458 | "ValueError" "Warning" "WindowsError" "ZeroDivisionError" |
| 135 | "StopIteration" "SyntaxError" "SyntaxWarning" "SystemError" | 459 | ;; Python 2: |
| 136 | "SystemExit" "TabError" "TypeError" "UnboundLocalError" | 460 | "StandardError" |
| 137 | "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError" | 461 | ;; Python 3: |
| 138 | "UnicodeTranslateError" "UnicodeWarning" "UserWarning" | 462 | "BufferError" "BytesWarning" "IndentationError" "ResourceWarning" |
| 139 | "ValueError" "Warning" "ZeroDivisionError" | 463 | "TabError") |
| 140 | ;; Python 2.7 | 464 | symbol-end) . font-lock-type-face) |
| 141 | "BufferError" "BytesWarning" "WindowsError") symbol-end) | 465 | ;; Builtins |
| 142 | . font-lock-type-face) | 466 | (,(rx symbol-start |
| 143 | (,(rx (or line-start (not (any ". \t"))) (* (any " \t")) symbol-start | 467 | (or |
| 144 | (group (or | 468 | "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod" |
| 145 | ;; callable built-ins, fontified when not appearing as | 469 | "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate" |
| 146 | ;; object attributes | 470 | "eval" "filter" "float" "format" "frozenset" "getattr" "globals" |
| 147 | "abs" "all" "any" "apply" "basestring" "bool" "buffer" "callable" | 471 | "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance" |
| 148 | "chr" "classmethod" "cmp" "coerce" "compile" "complex" | 472 | "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview" |
| 149 | "copyright" "credits" "delattr" "dict" "dir" "divmod" | 473 | "min" "next" "object" "oct" "open" "ord" "pow" "print" "property" |
| 150 | "enumerate" "eval" "execfile" "exit" "file" "filter" "float" | 474 | "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted" |
| 151 | "frozenset" "getattr" "globals" "hasattr" "hash" "help" | 475 | "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip" |
| 152 | "hex" "id" "input" "int" "intern" "isinstance" "issubclass" | 476 | "__import__" |
| 153 | "iter" "len" "license" "list" "locals" "long" "map" "max" | 477 | ;; Python 2: |
| 154 | "min" "object" "oct" "open" "ord" "pow" "property" "quit" | 478 | "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce" |
| 155 | "range" "raw_input" "reduce" "reload" "repr" "reversed" | 479 | "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce" |
| 156 | "round" "set" "setattr" "slice" "sorted" "staticmethod" | 480 | "intern" |
| 157 | "str" "sum" "super" "tuple" "type" "unichr" "unicode" "vars" | 481 | ;; Python 3: |
| 158 | "xrange" "zip" | 482 | "ascii" "bytearray" "bytes" "exec" |
| 159 | ;; Python 2.7. | 483 | ;; Extra: |
| 160 | "bin" "bytearray" "bytes" "format" "memoryview" "next" "print" | 484 | "__all__" "__doc__" "__name__" "__package__") |
| 161 | )) symbol-end) | 485 | symbol-end) . font-lock-builtin-face) |
| 162 | (1 font-lock-builtin-face)) | 486 | ;; assignments |
| 163 | (,(rx symbol-start (or | 487 | ;; support for a = b = c = 5 |
| 164 | ;; other built-ins | 488 | (,(lambda (limit) |
| 165 | "True" "False" "None" "Ellipsis" | 489 | (let ((re (python-rx (group (+ (any word ?. ?_))) |
| 166 | "_" "__debug__" "__doc__" "__import__" "__name__" "__package__") | 490 | (? ?\[ (+ (not (any ?\]))) ?\]) (* space) |
| 167 | symbol-end) | 491 | assignment-operator))) |
| 168 | . font-lock-builtin-face))) | 492 | (when (re-search-forward re limit t) |
| 493 | (while (and (python-syntax-context 'paren) | ||
| 494 | (re-search-forward re limit t))) | ||
| 495 | (if (not (or (python-syntax-context 'paren) | ||
| 496 | (equal (char-after (point-marker)) ?=))) | ||
| 497 | t | ||
| 498 | (set-match-data nil))))) | ||
| 499 | (1 font-lock-variable-name-face nil nil)) | ||
| 500 | ;; support for a, b, c = (1, 2, 3) | ||
| 501 | (,(lambda (limit) | ||
| 502 | (let ((re (python-rx (group (+ (any word ?. ?_))) (* space) | ||
| 503 | (* ?, (* space) (+ (any word ?. ?_)) (* space)) | ||
| 504 | ?, (* space) (+ (any word ?. ?_)) (* space) | ||
| 505 | assignment-operator))) | ||
| 506 | (when (and (re-search-forward re limit t) | ||
| 507 | (goto-char (nth 3 (match-data)))) | ||
| 508 | (while (and (python-syntax-context 'paren) | ||
| 509 | (re-search-forward re limit t)) | ||
| 510 | (goto-char (nth 3 (match-data)))) | ||
| 511 | (if (not (python-syntax-context 'paren)) | ||
| 512 | t | ||
| 513 | (set-match-data nil))))) | ||
| 514 | (1 font-lock-variable-name-face nil nil)))) | ||
| 169 | 515 | ||
| 170 | (defconst python-syntax-propertize-function | 516 | (defconst python-syntax-propertize-function |
| 171 | ;; Make outer chars of matching triple-quote sequences into generic | ||
| 172 | ;; string delimiters. Fixme: Is there a better way? | ||
| 173 | ;; First avoid a sequence preceded by an odd number of backslashes. | ||
| 174 | (syntax-propertize-rules | 517 | (syntax-propertize-rules |
| 175 | (;; ¡Backrefs don't work in syntax-propertize-rules! | 518 | ((python-rx string-delimiter) |
| 176 | (concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix. | 519 | (0 (ignore (python-syntax-stringify)))))) |
| 177 | "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)") | 520 | |
| 178 | (3 (ignore (python-quote-syntax)))) | 521 | (defsubst python-syntax-count-quotes (quote-char &optional point limit) |
| 179 | ;; This doesn't really help. | 522 | "Count number of quotes around point (max is 3). |
| 180 | ;;((rx (and ?\\ (group ?\n))) (1 " ")) | 523 | QUOTE-CHAR is the quote char to count. Optional argument POINT is |
| 181 | )) | 524 | the point where scan starts (defaults to current point) and LIMIT |
| 182 | 525 | is used to limit the scan." | |
| 183 | (defun python-quote-syntax () | 526 | (let ((i 0)) |
| 184 | "Put `syntax-table' property correctly on triple quote. | 527 | (while (and (< i 3) |
| 185 | Used for syntactic keywords. N is the match number (1, 2 or 3)." | 528 | (or (not limit) (< (+ point i) limit)) |
| 186 | ;; Given a triple quote, we have to check the context to know | 529 | (eq (char-after (+ point i)) quote-char)) |
| 187 | ;; whether this is an opening or closing triple or whether it's | 530 | (cl-incf i)) |
| 188 | ;; quoted anyhow, and should be ignored. (For that we need to do | 531 | i)) |
| 189 | ;; the same job as `syntax-ppss' to be correct and it seems to be OK | 532 | |
| 190 | ;; to use it here despite initial worries.) We also have to sort | 533 | (defun python-syntax-stringify () |
| 191 | ;; out a possible prefix -- well, we don't _have_ to, but I think it | 534 | "Put `syntax-table' property correctly on single/triple quotes." |
| 192 | ;; should be treated as part of the string. | 535 | (let* ((num-quotes (length (match-string-no-properties 1))) |
| 193 | 536 | (ppss (prog2 | |
| 194 | ;; Test cases: | 537 | (backward-char num-quotes) |
| 195 | ;; ur"""ar""" x='"' # """ | 538 | (syntax-ppss) |
| 196 | ;; x = ''' """ ' a | 539 | (forward-char num-quotes))) |
| 197 | ;; ''' | 540 | (string-start (and (not (nth 4 ppss)) (nth 8 ppss))) |
| 198 | ;; x '"""' x """ \"""" x | 541 | (quote-starting-pos (- (point) num-quotes)) |
| 199 | (save-excursion | 542 | (quote-ending-pos (point)) |
| 200 | (goto-char (match-beginning 0)) | 543 | (num-closing-quotes |
| 201 | (let ((syntax (save-match-data (syntax-ppss)))) | 544 | (and string-start |
| 202 | (cond | 545 | (python-syntax-count-quotes |
| 203 | ((eq t (nth 3 syntax)) ; after unclosed fence | 546 | (char-before) string-start quote-starting-pos)))) |
| 204 | ;; Consider property for the last char if in a fenced string. | 547 | (cond ((and string-start (= num-closing-quotes 0)) |
| 205 | (goto-char (nth 8 syntax)) ; fence position | 548 | ;; This set of quotes doesn't match the string starting |
| 206 | (skip-chars-forward "uUrR") ; skip any prefix | 549 | ;; kind. Do nothing. |
| 207 | ;; Is it a matching sequence? | 550 | nil) |
| 208 | (if (eq (char-after) (char-after (match-beginning 2))) | 551 | ((not string-start) |
| 209 | (put-text-property (match-beginning 3) (match-end 3) | 552 | ;; This set of quotes delimit the start of a string. |
| 210 | 'syntax-table (string-to-syntax "|")))) | 553 | (put-text-property quote-starting-pos (1+ quote-starting-pos) |
| 211 | ((match-end 1) | 554 | 'syntax-table (string-to-syntax "|"))) |
| 212 | ;; Consider property for initial char, accounting for prefixes. | 555 | ((= num-quotes num-closing-quotes) |
| 213 | (put-text-property (match-beginning 1) (match-end 1) | 556 | ;; This set of quotes delimit the end of a string. |
| 214 | 'syntax-table (string-to-syntax "|"))) | 557 | (put-text-property (1- quote-ending-pos) quote-ending-pos |
| 215 | (t | 558 | 'syntax-table (string-to-syntax "|"))) |
| 216 | ;; Consider property for initial char, accounting for prefixes. | 559 | ((> num-quotes num-closing-quotes) |
| 217 | (put-text-property (match-beginning 2) (match-end 2) | 560 | ;; This may only happen whenever a triple quote is closing |
| 218 | 'syntax-table (string-to-syntax "|")))) | 561 | ;; a single quoted string. Add string delimiter syntax to |
| 219 | ))) | 562 | ;; all three quotes. |
| 220 | 563 | (put-text-property quote-starting-pos quote-ending-pos | |
| 221 | ;; This isn't currently in `font-lock-defaults' as probably not worth | 564 | 'syntax-table (string-to-syntax "|")))))) |
| 222 | ;; it -- we basically only mess with a few normally-symbol characters. | ||
| 223 | |||
| 224 | ;; (defun python-font-lock-syntactic-face-function (state) | ||
| 225 | ;; "`font-lock-syntactic-face-function' for Python mode. | ||
| 226 | ;; Returns the string or comment face as usual, with side effect of putting | ||
| 227 | ;; a `syntax-table' property on the inside of the string or comment which is | ||
| 228 | ;; the standard syntax table." | ||
| 229 | ;; (if (nth 3 state) | ||
| 230 | ;; (save-excursion | ||
| 231 | ;; (goto-char (nth 8 state)) | ||
| 232 | ;; (condition-case nil | ||
| 233 | ;; (forward-sexp) | ||
| 234 | ;; (error nil)) | ||
| 235 | ;; (put-text-property (1+ (nth 8 state)) (1- (point)) | ||
| 236 | ;; 'syntax-table (standard-syntax-table)) | ||
| 237 | ;; 'font-lock-string-face) | ||
| 238 | ;; (put-text-property (1+ (nth 8 state)) (line-end-position) | ||
| 239 | ;; 'syntax-table (standard-syntax-table)) | ||
| 240 | ;; 'font-lock-comment-face)) | ||
| 241 | |||
| 242 | ;;;; Keymap and syntax | ||
| 243 | |||
| 244 | (defvar python-mode-map | ||
| 245 | (let ((map (make-sparse-keymap))) | ||
| 246 | ;; Mostly taken from python-mode.el. | ||
| 247 | (define-key map ":" 'python-electric-colon) | ||
| 248 | (define-key map "\177" 'python-backspace) | ||
| 249 | (define-key map "\C-c<" 'python-shift-left) | ||
| 250 | (define-key map "\C-c>" 'python-shift-right) | ||
| 251 | (define-key map "\C-c\C-k" 'python-mark-block) | ||
| 252 | (define-key map "\C-c\C-d" 'python-pdbtrack-toggle-stack-tracking) | ||
| 253 | (define-key map "\C-c\C-n" 'python-next-statement) | ||
| 254 | (define-key map "\C-c\C-p" 'python-previous-statement) | ||
| 255 | (define-key map "\C-c\C-u" 'python-beginning-of-block) | ||
| 256 | (define-key map "\C-c\C-f" 'python-describe-symbol) | ||
| 257 | (define-key map "\C-c\C-w" 'python-check) | ||
| 258 | (define-key map "\C-c\C-v" 'python-check) ; a la sgml-mode | ||
| 259 | (define-key map "\C-c\C-s" 'python-send-string) | ||
| 260 | (define-key map [?\C-\M-x] 'python-send-defun) | ||
| 261 | (define-key map "\C-c\C-r" 'python-send-region) | ||
| 262 | (define-key map "\C-c\M-r" 'python-send-region-and-go) | ||
| 263 | (define-key map "\C-c\C-c" 'python-send-buffer) | ||
| 264 | (define-key map "\C-c\C-z" 'python-switch-to-python) | ||
| 265 | (define-key map "\C-c\C-m" 'python-load-file) | ||
| 266 | (define-key map "\C-c\C-l" 'python-load-file) ; a la cmuscheme | ||
| 267 | (substitute-key-definition 'complete-symbol 'completion-at-point | ||
| 268 | map global-map) | ||
| 269 | (define-key map "\C-c\C-i" 'python-find-imports) | ||
| 270 | (define-key map "\C-c\C-t" 'python-expand-template) | ||
| 271 | (easy-menu-define python-menu map "Python Mode menu" | ||
| 272 | `("Python" | ||
| 273 | :help "Python-specific Features" | ||
| 274 | ["Shift region left" python-shift-left :active mark-active | ||
| 275 | :help "Shift by a single indentation step"] | ||
| 276 | ["Shift region right" python-shift-right :active mark-active | ||
| 277 | :help "Shift by a single indentation step"] | ||
| 278 | "-" | ||
| 279 | ["Mark block" python-mark-block | ||
| 280 | :help "Mark innermost block around point"] | ||
| 281 | ["Mark def/class" mark-defun | ||
| 282 | :help "Mark innermost definition around point"] | ||
| 283 | "-" | ||
| 284 | ["Start of block" python-beginning-of-block | ||
| 285 | :help "Go to start of innermost definition around point"] | ||
| 286 | ["End of block" python-end-of-block | ||
| 287 | :help "Go to end of innermost definition around point"] | ||
| 288 | ["Start of def/class" beginning-of-defun | ||
| 289 | :help "Go to start of innermost definition around point"] | ||
| 290 | ["End of def/class" end-of-defun | ||
| 291 | :help "Go to end of innermost definition around point"] | ||
| 292 | "-" | ||
| 293 | ("Templates..." | ||
| 294 | :help "Expand templates for compound statements" | ||
| 295 | :filter (lambda (&rest junk) | ||
| 296 | (abbrev-table-menu python-mode-abbrev-table))) | ||
| 297 | "-" | ||
| 298 | ["Start interpreter" run-python | ||
| 299 | :help "Run `inferior' Python in separate buffer"] | ||
| 300 | ["Import/reload file" python-load-file | ||
| 301 | :help "Load into inferior Python session"] | ||
| 302 | ["Eval buffer" python-send-buffer | ||
| 303 | :help "Evaluate buffer en bloc in inferior Python session"] | ||
| 304 | ["Eval region" python-send-region :active mark-active | ||
| 305 | :help "Evaluate region en bloc in inferior Python session"] | ||
| 306 | ["Eval def/class" python-send-defun | ||
| 307 | :help "Evaluate current definition in inferior Python session"] | ||
| 308 | ["Switch to interpreter" python-switch-to-python | ||
| 309 | :help "Switch to inferior Python buffer"] | ||
| 310 | ["Set default process" python-set-proc | ||
| 311 | :help "Make buffer's inferior process the default" | ||
| 312 | :active (buffer-live-p python-buffer)] | ||
| 313 | ["Check file" python-check :help "Run pychecker"] | ||
| 314 | ["Debugger" pdb :help "Run pdb under GUD"] | ||
| 315 | "-" | ||
| 316 | ["Help on symbol" python-describe-symbol | ||
| 317 | :help "Use pydoc on symbol at point"] | ||
| 318 | ["Complete symbol" completion-at-point | ||
| 319 | :help "Complete (qualified) symbol before point"] | ||
| 320 | ["Find function" python-find-function | ||
| 321 | :help "Try to find source definition of function at point"] | ||
| 322 | ["Update imports" python-find-imports | ||
| 323 | :help "Update list of top-level imports for completion"])) | ||
| 324 | map)) | ||
| 325 | ;; Fixme: add toolbar stuff for useful things like symbol help, send | ||
| 326 | ;; region, at least. (Shouldn't be specific to Python, obviously.) | ||
| 327 | ;; eric has items including: (un)indent, (un)comment, restart script, | ||
| 328 | ;; run script, debug script; also things for profiling, unit testing. | ||
| 329 | 565 | ||
| 330 | (defvar python-mode-syntax-table | 566 | (defvar python-mode-syntax-table |
| 331 | (let ((table (make-syntax-table))) | 567 | (let ((table (make-syntax-table))) |
| 332 | ;; Give punctuation syntax to ASCII that normally has symbol | 568 | ;; Give punctuation syntax to ASCII that normally has symbol |
| 333 | ;; syntax or has word syntax and isn't a letter. | 569 | ;; syntax or has word syntax and isn't a letter. |
| 334 | (let ((symbol (string-to-syntax "_")) | 570 | (let ((symbol (string-to-syntax "_")) |
| 335 | (sst (standard-syntax-table))) | 571 | (sst (standard-syntax-table))) |
| 336 | (dotimes (i 128) | 572 | (dotimes (i 128) |
| 337 | (unless (= i ?_) | 573 | (unless (= i ?_) |
| 338 | (if (equal symbol (aref sst i)) | 574 | (if (equal symbol (aref sst i)) |
| 339 | (modify-syntax-entry i "." table))))) | 575 | (modify-syntax-entry i "." table))))) |
| 340 | (modify-syntax-entry ?$ "." table) | 576 | (modify-syntax-entry ?$ "." table) |
| 341 | (modify-syntax-entry ?% "." table) | 577 | (modify-syntax-entry ?% "." table) |
| 342 | ;; exceptions | 578 | ;; exceptions |
| @@ -344,1880 +580,2024 @@ Used for syntactic keywords. N is the match number (1, 2 or 3)." | |||
| 344 | (modify-syntax-entry ?\n ">" table) | 580 | (modify-syntax-entry ?\n ">" table) |
| 345 | (modify-syntax-entry ?' "\"" table) | 581 | (modify-syntax-entry ?' "\"" table) |
| 346 | (modify-syntax-entry ?` "$" table) | 582 | (modify-syntax-entry ?` "$" table) |
| 347 | table)) | ||
| 348 | |||
| 349 | ;;;; Utility stuff | ||
| 350 | |||
| 351 | (defsubst python-in-string/comment () | ||
| 352 | "Return non-nil if point is in a Python literal (a comment or string)." | ||
| 353 | ;; We don't need to save the match data. | ||
| 354 | (nth 8 (syntax-ppss))) | ||
| 355 | |||
| 356 | (defconst python-space-backslash-table | ||
| 357 | (let ((table (copy-syntax-table python-mode-syntax-table))) | ||
| 358 | (modify-syntax-entry ?\\ " " table) | ||
| 359 | table) | 583 | table) |
| 360 | "`python-mode-syntax-table' with backslash given whitespace syntax.") | 584 | "Syntax table for Python files.") |
| 361 | |||
| 362 | (defun python-skip-comments/blanks (&optional backward) | ||
| 363 | "Skip comments and blank lines. | ||
| 364 | BACKWARD non-nil means go backwards, otherwise go forwards. | ||
| 365 | Backslash is treated as whitespace so that continued blank lines | ||
| 366 | are skipped. Doesn't move out of comments -- should be outside | ||
| 367 | or at end of line." | ||
| 368 | (let ((arg (if backward | ||
| 369 | ;; If we're in a comment (including on the trailing | ||
| 370 | ;; newline), forward-comment doesn't move backwards out | ||
| 371 | ;; of it. Don't set the syntax table round this bit! | ||
| 372 | (let ((syntax (syntax-ppss))) | ||
| 373 | (if (nth 4 syntax) | ||
| 374 | (goto-char (nth 8 syntax))) | ||
| 375 | (- (point-max))) | ||
| 376 | (point-max)))) | ||
| 377 | (with-syntax-table python-space-backslash-table | ||
| 378 | (forward-comment arg)))) | ||
| 379 | |||
| 380 | (defun python-backslash-continuation-line-p () | ||
| 381 | "Non-nil if preceding line ends with backslash that is not in a comment." | ||
| 382 | (and (eq ?\\ (char-before (line-end-position 0))) | ||
| 383 | (not (syntax-ppss-context (syntax-ppss))))) | ||
| 384 | |||
| 385 | (defun python-continuation-line-p () | ||
| 386 | "Return non-nil if current line continues a previous one. | ||
| 387 | The criteria are that the previous line ends in a backslash outside | ||
| 388 | comments and strings, or that point is within brackets/parens." | ||
| 389 | (or (python-backslash-continuation-line-p) | ||
| 390 | (let ((depth (syntax-ppss-depth | ||
| 391 | (save-excursion ; syntax-ppss with arg changes point | ||
| 392 | (syntax-ppss (line-beginning-position)))))) | ||
| 393 | (or (> depth 0) | ||
| 394 | (if (< depth 0) ; Unbalanced brackets -- act locally | ||
| 395 | (save-excursion | ||
| 396 | (condition-case () | ||
| 397 | (progn (backward-up-list) t) ; actually within brackets | ||
| 398 | (error nil)))))))) | ||
| 399 | |||
| 400 | (defun python-comment-line-p () | ||
| 401 | "Return non-nil if and only if current line has only a comment." | ||
| 402 | (save-excursion | ||
| 403 | (end-of-line) | ||
| 404 | (when (eq 'comment (syntax-ppss-context (syntax-ppss))) | ||
| 405 | (back-to-indentation) | ||
| 406 | (looking-at (rx (or (syntax comment-start) line-end)))))) | ||
| 407 | 585 | ||
| 408 | (defun python-blank-line-p () | 586 | (defvar python-dotty-syntax-table |
| 409 | "Return non-nil if and only if current line is blank." | 587 | (let ((table (make-syntax-table python-mode-syntax-table))) |
| 410 | (save-excursion | 588 | (modify-syntax-entry ?. "w" table) |
| 411 | (beginning-of-line) | 589 | (modify-syntax-entry ?_ "w" table) |
| 412 | (looking-at "\\s-*$"))) | 590 | table) |
| 413 | 591 | "Dotty syntax table for Python files. | |
| 414 | (defun python-beginning-of-string () | 592 | It makes underscores and dots word constituent chars.") |
| 415 | "Go to beginning of string around point. | ||
| 416 | Do nothing if not in string." | ||
| 417 | (let ((state (syntax-ppss))) | ||
| 418 | (when (eq 'string (syntax-ppss-context state)) | ||
| 419 | (goto-char (nth 8 state))))) | ||
| 420 | |||
| 421 | (defun python-open-block-statement-p (&optional bos) | ||
| 422 | "Return non-nil if statement at point opens a block. | ||
| 423 | BOS non-nil means point is known to be at beginning of statement." | ||
| 424 | (save-excursion | ||
| 425 | (unless bos (python-beginning-of-statement)) | ||
| 426 | (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def" | ||
| 427 | "class" "try" "except" "finally" "with") | ||
| 428 | symbol-end))))) | ||
| 429 | |||
| 430 | (defun python-close-block-statement-p (&optional bos) | ||
| 431 | "Return non-nil if current line is a statement closing a block. | ||
| 432 | BOS non-nil means point is at beginning of statement. | ||
| 433 | The criteria are that the line isn't a comment or in string and | ||
| 434 | starts with keyword `raise', `break', `continue' or `pass'." | ||
| 435 | (save-excursion | ||
| 436 | (unless bos (python-beginning-of-statement)) | ||
| 437 | (back-to-indentation) | ||
| 438 | (looking-at (rx (or "return" "raise" "break" "continue" "pass") | ||
| 439 | symbol-end)))) | ||
| 440 | 593 | ||
| 441 | (defun python-outdent-p () | ||
| 442 | "Return non-nil if current line should outdent a level." | ||
| 443 | (save-excursion | ||
| 444 | (back-to-indentation) | ||
| 445 | (and (looking-at (rx (and (or "else" "finally" "except" "elif") | ||
| 446 | symbol-end))) | ||
| 447 | (not (python-in-string/comment)) | ||
| 448 | ;; Ensure there's a previous statement and move to it. | ||
| 449 | (zerop (python-previous-statement)) | ||
| 450 | (not (python-close-block-statement-p t)) | ||
| 451 | ;; Fixme: check this | ||
| 452 | (not (python-open-block-statement-p))))) | ||
| 453 | 594 | ||
| 454 | ;;;; Indentation. | 595 | ;;; Indentation |
| 455 | 596 | ||
| 456 | (defcustom python-indent 4 | 597 | (defcustom python-indent-offset 4 |
| 457 | "Number of columns for a unit of indentation in Python mode. | 598 | "Default indentation offset for Python." |
| 458 | See also `\\[python-guess-indent]'" | ||
| 459 | :group 'python | 599 | :group 'python |
| 460 | :type 'integer) | 600 | :type 'integer |
| 461 | (put 'python-indent 'safe-local-variable 'integerp) | 601 | :safe 'integerp) |
| 462 | 602 | ||
| 463 | (defcustom python-guess-indent t | 603 | (defcustom python-indent-guess-indent-offset t |
| 464 | "Non-nil means Python mode guesses `python-indent' for the buffer." | 604 | "Non-nil tells Python mode to guess `python-indent-offset' value." |
| 465 | :type 'boolean | 605 | :type 'boolean |
| 466 | :group 'python) | ||
| 467 | |||
| 468 | (defcustom python-indent-string-contents t | ||
| 469 | "Non-nil means indent contents of multi-line strings together. | ||
| 470 | This means indent them the same as the preceding non-blank line. | ||
| 471 | Otherwise preserve their indentation. | ||
| 472 | |||
| 473 | This only applies to `doc' strings, i.e. those that form statements; | ||
| 474 | the indentation is preserved in others." | ||
| 475 | :type '(choice (const :tag "Align with preceding" t) | ||
| 476 | (const :tag "Preserve indentation" nil)) | ||
| 477 | :group 'python) | ||
| 478 | |||
| 479 | (defcustom python-honour-comment-indentation nil | ||
| 480 | "Non-nil means indent relative to preceding comment line. | ||
| 481 | Only do this for comments where the leading comment character is | ||
| 482 | followed by space. This doesn't apply to comment lines, which | ||
| 483 | are always indented in lines with preceding comments." | ||
| 484 | :type 'boolean | ||
| 485 | :group 'python) | ||
| 486 | |||
| 487 | (defcustom python-continuation-offset 4 | ||
| 488 | "Number of columns of additional indentation for continuation lines. | ||
| 489 | Continuation lines follow a backslash-terminated line starting a | ||
| 490 | statement." | ||
| 491 | :group 'python | 606 | :group 'python |
| 492 | :type 'integer) | 607 | :safe 'booleanp) |
| 493 | |||
| 494 | |||
| 495 | (defcustom python-pdbtrack-do-tracking-p t | ||
| 496 | "*Controls whether the pdbtrack feature is enabled or not. | ||
| 497 | |||
| 498 | When non-nil, pdbtrack is enabled in all comint-based buffers, | ||
| 499 | e.g. shell interaction buffers and the *Python* buffer. | ||
| 500 | |||
| 501 | When using pdb to debug a Python program, pdbtrack notices the | ||
| 502 | pdb prompt and presents the line in the source file where the | ||
| 503 | program is stopped in a pop-up buffer. It's similar to what | ||
| 504 | gud-mode does for debugging C programs with gdb, but without | ||
| 505 | having to restart the program." | ||
| 506 | :type 'boolean | ||
| 507 | :group 'python) | ||
| 508 | (make-variable-buffer-local 'python-pdbtrack-do-tracking-p) | ||
| 509 | 608 | ||
| 510 | (defcustom python-pdbtrack-minor-mode-string " PDB" | 609 | (define-obsolete-variable-alias |
| 511 | "*Minor-mode sign to be displayed when pdbtrack is active." | 610 | 'python-indent 'python-indent-offset "24.3") |
| 512 | :type 'string | ||
| 513 | :group 'python) | ||
| 514 | 611 | ||
| 515 | ;; Add a designator to the minor mode strings | 612 | (define-obsolete-variable-alias |
| 516 | (or (assq 'python-pdbtrack-is-tracking-p minor-mode-alist) | 613 | 'python-guess-indent 'python-indent-guess-indent-offset "24.3") |
| 517 | (push '(python-pdbtrack-is-tracking-p python-pdbtrack-minor-mode-string) | ||
| 518 | minor-mode-alist)) | ||
| 519 | |||
| 520 | (defcustom python-shell-prompt-alist | ||
| 521 | '(("ipython" . "^In \\[[0-9]+\\]: *") | ||
| 522 | (t . "^>>> ")) | ||
| 523 | "Alist of Python input prompts. | ||
| 524 | Each element has the form (PROGRAM . REGEXP), where PROGRAM is | ||
| 525 | the value of `python-python-command' for the python process and | ||
| 526 | REGEXP is a regular expression matching the Python prompt. | ||
| 527 | PROGRAM can also be t, which specifies the default when no other | ||
| 528 | element matches `python-python-command'." | ||
| 529 | :type 'string | ||
| 530 | :group 'python | ||
| 531 | :version "24.1") | ||
| 532 | |||
| 533 | (defcustom python-shell-continuation-prompt-alist | ||
| 534 | '(("ipython" . "^ [.][.][.]+: *") | ||
| 535 | (t . "^[.][.][.] ")) | ||
| 536 | "Alist of Python continued-line prompts. | ||
| 537 | Each element has the form (PROGRAM . REGEXP), where PROGRAM is | ||
| 538 | the value of `python-python-command' for the python process and | ||
| 539 | REGEXP is a regular expression matching the Python prompt for | ||
| 540 | continued lines. | ||
| 541 | PROGRAM can also be t, which specifies the default when no other | ||
| 542 | element matches `python-python-command'." | ||
| 543 | :type 'string | ||
| 544 | :group 'python | ||
| 545 | :version "24.1") | ||
| 546 | 614 | ||
| 547 | (defvar python-pdbtrack-is-tracking-p nil) | 615 | (defvar python-indent-current-level 0 |
| 616 | "Current indentation level `python-indent-line-function' is using.") | ||
| 548 | 617 | ||
| 549 | (defconst python-pdbtrack-stack-entry-regexp | 618 | (defvar python-indent-levels '(0) |
| 550 | "^> \\(.*\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()" | 619 | "Levels of indentation available for `python-indent-line-function'.") |
| 551 | "Regular expression pdbtrack uses to find a stack trace entry.") | ||
| 552 | 620 | ||
| 553 | (defconst python-pdbtrack-input-prompt "\n[(<]*[Ii]?[Pp]db[>)]+ " | 621 | (defvar python-indent-dedenters '("else" "elif" "except" "finally") |
| 554 | "Regular expression pdbtrack uses to recognize a pdb prompt.") | 622 | "List of words that should be dedented. |
| 623 | These make `python-indent-calculate-indentation' subtract the value of | ||
| 624 | `python-indent-offset'.") | ||
| 555 | 625 | ||
| 556 | (defconst python-pdbtrack-track-range 10000 | 626 | (defun python-indent-guess-indent-offset () |
| 557 | "Max number of characters from end of buffer to search for stack entry.") | 627 | "Guess and set `python-indent-offset' for the current buffer." |
| 558 | |||
| 559 | (defun python-guess-indent () | ||
| 560 | "Guess step for indentation of current buffer. | ||
| 561 | Set `python-indent' locally to the value guessed." | ||
| 562 | (interactive) | 628 | (interactive) |
| 563 | (save-excursion | 629 | (save-excursion |
| 564 | (save-restriction | 630 | (save-restriction |
| 565 | (widen) | 631 | (widen) |
| 566 | (goto-char (point-min)) | 632 | (goto-char (point-min)) |
| 567 | (let (done indent) | 633 | (let ((block-end)) |
| 568 | (while (and (not done) (not (eobp))) | 634 | (while (and (not block-end) |
| 569 | (when (and (re-search-forward (rx ?: (0+ space) | 635 | (re-search-forward |
| 570 | (or (syntax comment-start) | 636 | (python-rx line-start block-start) nil t)) |
| 571 | line-end)) | 637 | (when (and |
| 572 | nil 'move) | 638 | (not (python-syntax-context-type)) |
| 573 | (python-open-block-statement-p)) | 639 | (progn |
| 574 | (save-excursion | 640 | (goto-char (line-end-position)) |
| 575 | (python-beginning-of-statement) | 641 | (python-util-forward-comment -1) |
| 576 | (let ((initial (current-indentation))) | 642 | (if (equal (char-before) ?:) |
| 577 | (if (zerop (python-next-statement)) | 643 | t |
| 578 | (setq indent (- (current-indentation) initial))) | 644 | (forward-line 1) |
| 579 | (if (and indent (>= indent 2) (<= indent 8)) ; sanity check | 645 | (when (python-info-block-continuation-line-p) |
| 580 | (setq done t)))))) | 646 | (while (and (python-info-continuation-line-p) |
| 581 | (when done | 647 | (not (eobp))) |
| 582 | (when (/= indent (default-value 'python-indent)) | 648 | (forward-line 1)) |
| 583 | (set (make-local-variable 'python-indent) indent) | 649 | (python-util-forward-comment -1) |
| 584 | (unless (= tab-width python-indent) | 650 | (when (equal (char-before) ?:) |
| 585 | (setq indent-tabs-mode nil))) | 651 | t))))) |
| 586 | indent))))) | 652 | (setq block-end (point-marker)))) |
| 587 | 653 | (let ((indentation | |
| 588 | ;; Alist of possible indentations and start of statement they would | 654 | (when block-end |
| 589 | ;; close. Used in indentation cycling (below). | 655 | (goto-char block-end) |
| 590 | (defvar python-indent-list nil | 656 | (python-util-forward-comment) |
| 591 | "Internal use.") | 657 | (current-indentation)))) |
| 592 | ;; Length of the above | 658 | (if indentation |
| 593 | (defvar python-indent-list-length nil | 659 | (setq python-indent-offset indentation) |
| 594 | "Internal use.") | 660 | (message "Can't guess python-indent-offset, using defaults: %s" |
| 595 | ;; Current index into the alist. | 661 | python-indent-offset))))))) |
| 596 | (defvar python-indent-index nil | 662 | |
| 597 | "Internal use.") | 663 | (defun python-indent-context () |
| 598 | 664 | "Get information on indentation context. | |
| 599 | (defun python-calculate-indentation () | 665 | Context information is returned with a cons with the form: |
| 600 | "Calculate Python indentation for line at point." | 666 | \(STATUS . START) |
| 601 | (setq python-indent-list nil | 667 | |
| 602 | python-indent-list-length 1) | 668 | Where status can be any of the following symbols: |
| 603 | (save-excursion | 669 | * inside-paren: If point in between (), {} or [] |
| 604 | (beginning-of-line) | 670 | * inside-string: If point is inside a string |
| 605 | (let ((syntax (syntax-ppss)) | 671 | * after-backslash: Previous line ends in a backslash |
| 606 | start) | 672 | * after-beginning-of-block: Point is after beginning of block |
| 607 | (cond | 673 | * after-line: Point is after normal line |
| 608 | ((eq 'string (syntax-ppss-context syntax)) ; multi-line string | 674 | * no-indent: Point is at beginning of buffer or other special case |
| 609 | (if (not python-indent-string-contents) | 675 | START is the buffer position where the sexp starts." |
| 610 | (current-indentation) | 676 | (save-restriction |
| 611 | ;; Only respect `python-indent-string-contents' in doc | 677 | (widen) |
| 612 | ;; strings (defined as those which form statements). | 678 | (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss))) |
| 613 | (if (not (save-excursion | 679 | (start)) |
| 614 | (python-beginning-of-statement) | 680 | (cons |
| 615 | (looking-at (rx (or (syntax string-delimiter) | 681 | (cond |
| 616 | (syntax string-quote)))))) | 682 | ;; Beginning of buffer |
| 617 | (current-indentation) | 683 | ((save-excursion |
| 618 | ;; Find indentation of preceding non-blank line within string. | 684 | (goto-char (line-beginning-position)) |
| 619 | (setq start (nth 8 syntax)) | 685 | (bobp)) |
| 620 | (forward-line -1) | 686 | 'no-indent) |
| 621 | (while (and (< start (point)) (looking-at "\\s-*$")) | 687 | ;; Inside string |
| 622 | (forward-line -1)) | 688 | ((setq start (python-syntax-context 'string ppss)) |
| 623 | (current-indentation)))) | 689 | 'inside-string) |
| 624 | ((python-continuation-line-p) ; after backslash, or bracketed | 690 | ;; Inside a paren |
| 625 | (let ((point (point)) | 691 | ((setq start (python-syntax-context 'paren ppss)) |
| 626 | (open-start (cadr syntax)) | 692 | 'inside-paren) |
| 627 | (backslash (python-backslash-continuation-line-p)) | 693 | ;; After backslash |
| 628 | (colon (eq ?: (char-before (1- (line-beginning-position)))))) | 694 | ((setq start (when (not (or (python-syntax-context 'string ppss) |
| 629 | (if open-start | 695 | (python-syntax-context 'comment ppss))) |
| 630 | ;; Inside bracketed expression. | 696 | (let ((line-beg-pos (line-beginning-position))) |
| 631 | (progn | 697 | (when (python-info-line-ends-backslash-p |
| 632 | (goto-char (1+ open-start)) | 698 | (1- line-beg-pos)) |
| 633 | ;; Look for first item in list (preceding point) and | 699 | (- line-beg-pos 2))))) |
| 634 | ;; align with it, if found. | 700 | 'after-backslash) |
| 635 | (if (with-syntax-table python-space-backslash-table | 701 | ;; After beginning of block |
| 636 | (let ((parse-sexp-ignore-comments t)) | 702 | ((setq start (save-excursion |
| 637 | (condition-case () | 703 | (when (progn |
| 638 | (progn (forward-sexp) | 704 | (back-to-indentation) |
| 639 | (backward-sexp) | 705 | (python-util-forward-comment -1) |
| 640 | (< (point) point)) | 706 | (equal (char-before) ?:)) |
| 641 | (error nil)))) | 707 | ;; Move to the first block start that's not in within |
| 642 | ;; Extra level if we're backslash-continued or | 708 | ;; a string, comment or paren and that's not a |
| 643 | ;; following a key. | 709 | ;; continuation line. |
| 644 | (if (or backslash colon) | 710 | (while (and (re-search-backward |
| 645 | (+ python-indent (current-column)) | 711 | (python-rx block-start) nil t) |
| 646 | (current-column)) | 712 | (or |
| 647 | ;; Otherwise indent relative to statement start, one | 713 | (python-syntax-context-type) |
| 648 | ;; level per bracketing level. | 714 | (python-info-continuation-line-p)))) |
| 649 | (goto-char (1+ open-start)) | 715 | (when (looking-at (python-rx block-start)) |
| 650 | (python-beginning-of-statement) | 716 | (point-marker))))) |
| 651 | (+ (current-indentation) (* (car syntax) python-indent)))) | 717 | 'after-beginning-of-block) |
| 652 | ;; Otherwise backslash-continued. | 718 | ;; After normal line |
| 653 | (forward-line -1) | 719 | ((setq start (save-excursion |
| 654 | (if (python-continuation-line-p) | 720 | (back-to-indentation) |
| 655 | ;; We're past first continuation line. Align with | 721 | (skip-chars-backward (rx (or whitespace ?\n))) |
| 656 | ;; previous line. | 722 | (python-nav-beginning-of-statement) |
| 657 | (current-indentation) | 723 | (point-marker))) |
| 658 | ;; First continuation line. Indent one step, with an | 724 | 'after-line) |
| 659 | ;; extra one if statement opens a block. | 725 | ;; Do not indent |
| 660 | (python-beginning-of-statement) | 726 | (t 'no-indent)) |
| 661 | (+ (current-indentation) python-continuation-offset | 727 | start)))) |
| 662 | (if (python-open-block-statement-p t) | 728 | |
| 663 | python-indent | 729 | (defun python-indent-calculate-indentation () |
| 664 | 0)))))) | 730 | "Calculate correct indentation offset for the current line." |
| 665 | ((bobp) 0) | 731 | (let* ((indentation-context (python-indent-context)) |
| 666 | ;; Fixme: Like python-mode.el; not convinced by this. | 732 | (context-status (car indentation-context)) |
| 667 | ((looking-at (rx (0+ space) (syntax comment-start) | 733 | (context-start (cdr indentation-context))) |
| 668 | (not (any " \t\n")))) ; non-indentable comment | 734 | (save-restriction |
| 669 | (current-indentation)) | 735 | (widen) |
| 670 | ((and python-honour-comment-indentation | 736 | (save-excursion |
| 671 | ;; Back over whitespace, newlines, non-indentable comments. | 737 | (pcase context-status |
| 672 | (catch 'done | 738 | (`no-indent 0) |
| 673 | (while (cond ((bobp) nil) | 739 | ;; When point is after beginning of block just add one level |
| 674 | ((not (forward-comment -1)) | 740 | ;; of indentation relative to the context-start |
| 675 | nil) ; not at comment start | 741 | (`after-beginning-of-block |
| 676 | ;; Now at start of comment -- trailing one? | 742 | (goto-char context-start) |
| 677 | ((/= (current-column) (current-indentation)) | 743 | (+ (current-indentation) python-indent-offset)) |
| 678 | nil) | 744 | ;; When after a simple line just use previous line |
| 679 | ;; Indentable comment, like python-mode.el? | 745 | ;; indentation, in the case current line starts with a |
| 680 | ((and (looking-at (rx (syntax comment-start) | 746 | ;; `python-indent-dedenters' de-indent one level. |
| 681 | (or space line-end))) | 747 | (`after-line |
| 682 | (/= 0 (current-column))) | 748 | (- |
| 683 | (throw 'done (current-column))) | 749 | (save-excursion |
| 684 | ;; Else skip it (loop). | 750 | (goto-char context-start) |
| 685 | (t)))))) | 751 | (current-indentation)) |
| 686 | (t | 752 | (if (progn |
| 687 | (python-indentation-levels) | 753 | (back-to-indentation) |
| 688 | ;; Prefer to indent comments with an immediately-following | 754 | (looking-at (regexp-opt python-indent-dedenters))) |
| 689 | ;; statement, e.g. | 755 | python-indent-offset |
| 690 | ;; ... | 756 | 0))) |
| 691 | ;; # ... | 757 | ;; When inside of a string, do nothing. just use the current |
| 692 | ;; def ... | 758 | ;; indentation. XXX: perhaps it would be a good idea to |
| 693 | (when (and (> python-indent-list-length 1) | 759 | ;; invoke standard text indentation here |
| 694 | (python-comment-line-p)) | 760 | (`inside-string |
| 695 | (forward-line) | 761 | (goto-char context-start) |
| 696 | (unless (python-comment-line-p) | 762 | (current-indentation)) |
| 697 | (let ((elt (assq (current-indentation) python-indent-list))) | 763 | ;; After backslash we have several possibilities. |
| 698 | (setq python-indent-list | 764 | (`after-backslash |
| 699 | (nconc (delete elt python-indent-list) | 765 | (cond |
| 700 | (list elt)))))) | 766 | ;; Check if current line is a dot continuation. For this |
| 701 | (caar (last python-indent-list))))))) | 767 | ;; the current line must start with a dot and previous |
| 702 | 768 | ;; line must contain a dot too. | |
| 703 | ;;;; Cycling through the possible indentations with successive TABs. | 769 | ((save-excursion |
| 704 | 770 | (back-to-indentation) | |
| 705 | ;; These don't need to be buffer-local since they're only relevant | 771 | (when (looking-at "\\.") |
| 706 | ;; during a cycle. | 772 | ;; If after moving one line back point is inside a paren it |
| 707 | 773 | ;; needs to move back until it's not anymore | |
| 708 | (defun python-initial-text () | 774 | (while (prog2 |
| 709 | "Text of line following indentation and ignoring any trailing comment." | 775 | (forward-line -1) |
| 710 | (save-excursion | 776 | (and (not (bobp)) |
| 711 | (buffer-substring (progn | 777 | (python-syntax-context 'paren)))) |
| 712 | (back-to-indentation) | 778 | (goto-char (line-end-position)) |
| 713 | (point)) | 779 | (while (and (re-search-backward |
| 714 | (progn | 780 | "\\." (line-beginning-position) t) |
| 715 | (end-of-line) | 781 | (python-syntax-context-type))) |
| 716 | (forward-comment -1) | 782 | (if (and (looking-at "\\.") |
| 717 | (point))))) | 783 | (not (python-syntax-context-type))) |
| 718 | 784 | ;; The indentation is the same column of the | |
| 719 | (defconst python-block-pairs | 785 | ;; first matching dot that's not inside a |
| 720 | '(("else" "if" "elif" "while" "for" "try" "except") | 786 | ;; comment, a string or a paren |
| 721 | ("elif" "if" "elif") | 787 | (current-column) |
| 722 | ("except" "try" "except") | 788 | ;; No dot found on previous line, just add another |
| 723 | ("finally" "else" "try" "except")) | 789 | ;; indentation level. |
| 724 | "Alist of keyword matches. | 790 | (+ (current-indentation) python-indent-offset))))) |
| 725 | The car of an element is a keyword introducing a statement which | 791 | ;; Check if prev line is a block continuation |
| 726 | can close a block opened by a keyword in the cdr.") | 792 | ((let ((block-continuation-start |
| 727 | 793 | (python-info-block-continuation-line-p))) | |
| 728 | (defun python-first-word () | 794 | (when block-continuation-start |
| 729 | "Return first word (actually symbol) on the line." | 795 | ;; If block-continuation-start is set jump to that |
| 730 | (save-excursion | 796 | ;; marker and use first column after the block start |
| 731 | (back-to-indentation) | 797 | ;; as indentation value. |
| 732 | (current-word t))) | 798 | (goto-char block-continuation-start) |
| 733 | 799 | (re-search-forward | |
| 734 | (defun python-indentation-levels () | 800 | (python-rx block-start (* space)) |
| 735 | "Return a list of possible indentations for this line. | 801 | (line-end-position) t) |
| 736 | It is assumed not to be a continuation line or in a multi-line string. | 802 | (current-column)))) |
| 737 | Includes the default indentation and those which would close all | 803 | ;; Check if current line is an assignment continuation |
| 738 | enclosing blocks. Elements of the list are actually pairs: | 804 | ((let ((assignment-continuation-start |
| 739 | \(INDENTATION . TEXT), where TEXT is the initial text of the | 805 | (python-info-assignment-continuation-line-p))) |
| 740 | corresponding block opening (or nil)." | 806 | (when assignment-continuation-start |
| 741 | (save-excursion | 807 | ;; If assignment-continuation is set jump to that |
| 742 | (let ((initial "") | 808 | ;; marker and use first column after the assignment |
| 743 | levels indent) | 809 | ;; operator as indentation value. |
| 744 | ;; Only one possibility immediately following a block open | 810 | (goto-char assignment-continuation-start) |
| 745 | ;; statement, assuming it doesn't have a `suite' on the same line. | 811 | (current-column)))) |
| 746 | (cond | 812 | (t |
| 747 | ((save-excursion (and (python-previous-statement) | 813 | (forward-line -1) |
| 748 | (python-open-block-statement-p t) | 814 | (goto-char (python-info-beginning-of-backslash)) |
| 749 | (setq indent (current-indentation)) | 815 | (if (save-excursion |
| 750 | ;; Check we don't have something like: | 816 | (and |
| 751 | ;; if ...: ... | 817 | (forward-line -1) |
| 752 | (if (progn (python-end-of-statement) | 818 | (goto-char |
| 753 | (python-skip-comments/blanks t) | 819 | (or (python-info-beginning-of-backslash) (point))) |
| 754 | (eq ?: (char-before))) | 820 | (python-info-line-ends-backslash-p))) |
| 755 | (setq indent (+ python-indent indent))))) | 821 | ;; The two previous lines ended in a backslash so we must |
| 756 | (push (cons indent initial) levels)) | 822 | ;; respect previous line indentation. |
| 757 | ;; Only one possibility for comment line immediately following | 823 | (current-indentation) |
| 758 | ;; another. | 824 | ;; What happens here is that we are dealing with the second |
| 759 | ((save-excursion | 825 | ;; line of a backslash continuation, in that case we just going |
| 760 | (when (python-comment-line-p) | 826 | ;; to add one indentation level. |
| 761 | (forward-line -1) | 827 | (+ (current-indentation) python-indent-offset))))) |
| 762 | (if (python-comment-line-p) | 828 | ;; When inside a paren there's a need to handle nesting |
| 763 | (push (cons (current-indentation) initial) levels))))) | 829 | ;; correctly |
| 764 | ;; Fixme: Maybe have a case here which indents (only) first | 830 | (`inside-paren |
| 765 | ;; line after a lambda. | 831 | (cond |
| 766 | (t | 832 | ;; If current line closes the outermost open paren use the |
| 767 | (let ((start (car (assoc (python-first-word) python-block-pairs)))) | 833 | ;; current indentation of the context-start line. |
| 768 | (python-previous-statement) | 834 | ((save-excursion |
| 769 | ;; Is this a valid indentation for the line of interest? | 835 | (skip-syntax-forward "\s" (line-end-position)) |
| 770 | (unless (or (if start ; potentially only outdentable | 836 | (when (and (looking-at (regexp-opt '(")" "]" "}"))) |
| 771 | ;; Check for things like: | 837 | (progn |
| 772 | ;; if ...: ... | 838 | (forward-char 1) |
| 773 | ;; else ...: | 839 | (not (python-syntax-context 'paren)))) |
| 774 | ;; where the second line need not be outdented. | 840 | (goto-char context-start) |
| 775 | (not (member (python-first-word) | 841 | (current-indentation)))) |
| 776 | (cdr (assoc start | 842 | ;; If open paren is contained on a line by itself add another |
| 777 | python-block-pairs))))) | 843 | ;; indentation level, else look for the first word after the |
| 778 | ;; Not sensible to indent to the same level as | 844 | ;; opening paren and use it's column position as indentation |
| 779 | ;; previous `return' &c. | 845 | ;; level. |
| 780 | (python-close-block-statement-p)) | 846 | ((let* ((content-starts-in-newline) |
| 781 | (push (cons (current-indentation) (python-initial-text)) | 847 | (indent |
| 782 | levels)) | 848 | (save-excursion |
| 783 | (while (python-beginning-of-block) | 849 | (if (setq content-starts-in-newline |
| 784 | (when (or (not start) | 850 | (progn |
| 785 | (member (python-first-word) | 851 | (goto-char context-start) |
| 786 | (cdr (assoc start python-block-pairs)))) | 852 | (forward-char) |
| 787 | (push (cons (current-indentation) (python-initial-text)) | 853 | (save-restriction |
| 788 | levels)))))) | 854 | (narrow-to-region |
| 789 | (prog1 (or levels (setq levels '((0 . "")))) | 855 | (line-beginning-position) |
| 790 | (setq python-indent-list levels | 856 | (line-end-position)) |
| 791 | python-indent-list-length (length python-indent-list)))))) | 857 | (python-util-forward-comment)) |
| 792 | 858 | (looking-at "$"))) | |
| 793 | ;; This is basically what `python-indent-line' would be if we didn't | 859 | (+ (current-indentation) python-indent-offset) |
| 794 | ;; do the cycling. | 860 | (current-column))))) |
| 795 | (defun python-indent-line-1 (&optional leave) | 861 | ;; Adjustments |
| 796 | "Subroutine of `python-indent-line'. | 862 | (cond |
| 797 | Does non-repeated indentation. LEAVE non-nil means leave | 863 | ;; If current line closes a nested open paren de-indent one |
| 798 | indentation if it is valid, i.e. one of the positions returned by | 864 | ;; level. |
| 799 | `python-calculate-indentation'." | 865 | ((progn |
| 800 | (let ((target (python-calculate-indentation)) | 866 | (back-to-indentation) |
| 801 | (pos (- (point-max) (point)))) | 867 | (looking-at (regexp-opt '(")" "]" "}")))) |
| 802 | (if (or (= target (current-indentation)) | 868 | (- indent python-indent-offset)) |
| 803 | ;; Maybe keep a valid indentation. | 869 | ;; If the line of the opening paren that wraps the current |
| 804 | (and leave python-indent-list | 870 | ;; line starts a block add another level of indentation to |
| 805 | (assq (current-indentation) python-indent-list))) | 871 | ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx |
| 806 | (if (< (current-column) (current-indentation)) | 872 | ((save-excursion |
| 807 | (back-to-indentation)) | 873 | (when (and content-starts-in-newline |
| 874 | (progn | ||
| 875 | (goto-char context-start) | ||
| 876 | (back-to-indentation) | ||
| 877 | (looking-at (python-rx block-start)))) | ||
| 878 | (+ indent python-indent-offset)))) | ||
| 879 | (t indent))))))))))) | ||
| 880 | |||
| 881 | (defun python-indent-calculate-levels () | ||
| 882 | "Calculate `python-indent-levels' and reset `python-indent-current-level'." | ||
| 883 | (let* ((indentation (python-indent-calculate-indentation)) | ||
| 884 | (remainder (% indentation python-indent-offset)) | ||
| 885 | (steps (/ (- indentation remainder) python-indent-offset))) | ||
| 886 | (setq python-indent-levels (list 0)) | ||
| 887 | (dotimes (step steps) | ||
| 888 | (push (* python-indent-offset (1+ step)) python-indent-levels)) | ||
| 889 | (when (not (eq 0 remainder)) | ||
| 890 | (push (+ (* python-indent-offset steps) remainder) python-indent-levels)) | ||
| 891 | (setq python-indent-levels (nreverse python-indent-levels)) | ||
| 892 | (setq python-indent-current-level (1- (length python-indent-levels))))) | ||
| 893 | |||
| 894 | (defun python-indent-toggle-levels () | ||
| 895 | "Toggle `python-indent-current-level' over `python-indent-levels'." | ||
| 896 | (setq python-indent-current-level (1- python-indent-current-level)) | ||
| 897 | (when (< python-indent-current-level 0) | ||
| 898 | (setq python-indent-current-level (1- (length python-indent-levels))))) | ||
| 899 | |||
| 900 | (defun python-indent-line (&optional force-toggle) | ||
| 901 | "Internal implementation of `python-indent-line-function'. | ||
| 902 | Uses the offset calculated in | ||
| 903 | `python-indent-calculate-indentation' and available levels | ||
| 904 | indicated by the variable `python-indent-levels' to set the | ||
| 905 | current indentation. | ||
| 906 | |||
| 907 | When the variable `last-command' is equal to | ||
| 908 | `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles | ||
| 909 | levels indicated in the variable `python-indent-levels' by | ||
| 910 | setting the current level in the variable | ||
| 911 | `python-indent-current-level'. | ||
| 912 | |||
| 913 | When the variable `last-command' is not equal to | ||
| 914 | `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates | ||
| 915 | possible indentation levels and saves it in the variable | ||
| 916 | `python-indent-levels'. Afterwards it sets the variable | ||
| 917 | `python-indent-current-level' correctly so offset is equal | ||
| 918 | to (`nth' `python-indent-current-level' `python-indent-levels')" | ||
| 919 | (or | ||
| 920 | (and (or (and (eq this-command 'indent-for-tab-command) | ||
| 921 | (eq last-command this-command)) | ||
| 922 | force-toggle) | ||
| 923 | (not (equal python-indent-levels '(0))) | ||
| 924 | (or (python-indent-toggle-levels) t)) | ||
| 925 | (python-indent-calculate-levels)) | ||
| 926 | (let* ((starting-pos (point-marker)) | ||
| 927 | (indent-ending-position | ||
| 928 | (+ (line-beginning-position) (current-indentation))) | ||
| 929 | (follow-indentation-p | ||
| 930 | (or (bolp) | ||
| 931 | (and (<= (line-beginning-position) starting-pos) | ||
| 932 | (>= indent-ending-position starting-pos)))) | ||
| 933 | (next-indent (nth python-indent-current-level python-indent-levels))) | ||
| 934 | (unless (= next-indent (current-indentation)) | ||
| 808 | (beginning-of-line) | 935 | (beginning-of-line) |
| 809 | (delete-horizontal-space) | 936 | (delete-horizontal-space) |
| 810 | (indent-to target) | 937 | (indent-to next-indent) |
| 811 | (if (> (- (point-max) pos) (point)) | 938 | (goto-char starting-pos)) |
| 812 | (goto-char (- (point-max) pos)))))) | 939 | (and follow-indentation-p (back-to-indentation))) |
| 813 | 940 | (python-info-closing-block-message)) | |
| 814 | (defun python-indent-line () | 941 | |
| 815 | "Indent current line as Python code. | 942 | (defun python-indent-line-function () |
| 816 | When invoked via `indent-for-tab-command', cycle through possible | 943 | "`indent-line-function' for Python mode. |
| 817 | indentations for current line. The cycle is broken by a command | 944 | See `python-indent-line' for details." |
| 818 | different from `indent-for-tab-command', i.e. successive TABs do | 945 | (python-indent-line)) |
| 819 | the cycling." | 946 | |
| 820 | (interactive) | 947 | (defun python-indent-dedent-line () |
| 821 | (if (and (eq this-command 'indent-for-tab-command) | 948 | "De-indent current line." |
| 822 | (eq last-command this-command)) | 949 | (interactive "*") |
| 823 | (if (= 1 python-indent-list-length) | 950 | (when (and (not (python-syntax-comment-or-string-p)) |
| 824 | (message "Sole indentation") | 951 | (<= (point-marker) (save-excursion |
| 825 | (progn (setq python-indent-index | 952 | (back-to-indentation) |
| 826 | (% (1+ python-indent-index) python-indent-list-length)) | 953 | (point-marker))) |
| 827 | (beginning-of-line) | 954 | (> (current-column) 0)) |
| 828 | (delete-horizontal-space) | 955 | (python-indent-line t) |
| 829 | (indent-to (car (nth python-indent-index python-indent-list))) | 956 | t)) |
| 830 | (if (python-block-end-p) | 957 | |
| 831 | (let ((text (cdr (nth python-indent-index | 958 | (defun python-indent-dedent-line-backspace (arg) |
| 832 | python-indent-list)))) | 959 | "De-indent current line. |
| 833 | (if text | 960 | Argument ARG is passed to `backward-delete-char-untabify' when |
| 834 | (message "Closes: %s" text)))))) | 961 | point is not in between the indentation." |
| 835 | (python-indent-line-1) | 962 | (interactive "*p") |
| 836 | (setq python-indent-index (1- python-indent-list-length)))) | 963 | (when (not (python-indent-dedent-line)) |
| 964 | (backward-delete-char-untabify arg))) | ||
| 965 | (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede) | ||
| 837 | 966 | ||
| 838 | (defun python-indent-region (start end) | 967 | (defun python-indent-region (start end) |
| 839 | "`indent-region-function' for Python. | 968 | "Indent a python region automagically. |
| 840 | Leaves validly-indented lines alone, i.e. doesn't indent to | 969 | |
| 841 | another valid position." | 970 | Called from a program, START and END specify the region to indent." |
| 842 | (save-excursion | 971 | (let ((deactivate-mark nil)) |
| 843 | (goto-char end) | 972 | (save-excursion |
| 844 | (setq end (point-marker)) | 973 | (goto-char end) |
| 845 | (goto-char start) | 974 | (setq end (point-marker)) |
| 846 | (or (bolp) (forward-line 1)) | 975 | (goto-char start) |
| 847 | (while (< (point) end) | 976 | (or (bolp) (forward-line 1)) |
| 848 | (or (and (bolp) (eolp)) | 977 | (while (< (point) end) |
| 849 | (python-indent-line-1 t)) | 978 | (or (and (bolp) (eolp)) |
| 850 | (forward-line 1)) | 979 | (let (word) |
| 851 | (move-marker end nil))) | 980 | (forward-line -1) |
| 852 | 981 | (back-to-indentation) | |
| 853 | (defun python-block-end-p () | 982 | (setq word (current-word)) |
| 854 | "Non-nil if this is a line in a statement closing a block, | 983 | (forward-line 1) |
| 855 | or a blank line indented to where it would close a block." | 984 | (when (and word |
| 856 | (and (not (python-comment-line-p)) | 985 | ;; Don't mess with strings, unless it's the |
| 857 | (or (python-close-block-statement-p t) | 986 | ;; enclosing set of quotes. |
| 858 | (< (current-indentation) | 987 | (or (not (python-syntax-context 'string)) |
| 859 | (save-excursion | 988 | (eq |
| 860 | (python-previous-statement) | 989 | (syntax-after |
| 861 | (current-indentation)))))) | 990 | (+ (1- (point)) |
| 991 | (current-indentation) | ||
| 992 | (python-syntax-count-quotes (char-after) (point)))) | ||
| 993 | (string-to-syntax "|")))) | ||
| 994 | (beginning-of-line) | ||
| 995 | (delete-horizontal-space) | ||
| 996 | (indent-to (python-indent-calculate-indentation))))) | ||
| 997 | (forward-line 1)) | ||
| 998 | (move-marker end nil)))) | ||
| 999 | |||
| 1000 | (defun python-indent-shift-left (start end &optional count) | ||
| 1001 | "Shift lines contained in region START END by COUNT columns to the left. | ||
| 1002 | COUNT defaults to `python-indent-offset'. If region isn't | ||
| 1003 | active, the current line is shifted. The shifted region includes | ||
| 1004 | the lines in which START and END lie. An error is signaled if | ||
| 1005 | any lines in the region are indented less than COUNT columns." | ||
| 1006 | (interactive | ||
| 1007 | (if mark-active | ||
| 1008 | (list (region-beginning) (region-end) current-prefix-arg) | ||
| 1009 | (list (line-beginning-position) (line-end-position) current-prefix-arg))) | ||
| 1010 | (if count | ||
| 1011 | (setq count (prefix-numeric-value count)) | ||
| 1012 | (setq count python-indent-offset)) | ||
| 1013 | (when (> count 0) | ||
| 1014 | (let ((deactivate-mark nil)) | ||
| 1015 | (save-excursion | ||
| 1016 | (goto-char start) | ||
| 1017 | (while (< (point) end) | ||
| 1018 | (if (and (< (current-indentation) count) | ||
| 1019 | (not (looking-at "[ \t]*$"))) | ||
| 1020 | (error "Can't shift all lines enough")) | ||
| 1021 | (forward-line)) | ||
| 1022 | (indent-rigidly start end (- count)))))) | ||
| 1023 | |||
| 1024 | (add-to-list 'debug-ignored-errors "^Can't shift all lines enough") | ||
| 1025 | |||
| 1026 | (defun python-indent-shift-right (start end &optional count) | ||
| 1027 | "Shift lines contained in region START END by COUNT columns to the left. | ||
| 1028 | COUNT defaults to `python-indent-offset'. If region isn't | ||
| 1029 | active, the current line is shifted. The shifted region includes | ||
| 1030 | the lines in which START and END lie." | ||
| 1031 | (interactive | ||
| 1032 | (if mark-active | ||
| 1033 | (list (region-beginning) (region-end) current-prefix-arg) | ||
| 1034 | (list (line-beginning-position) (line-end-position) current-prefix-arg))) | ||
| 1035 | (let ((deactivate-mark nil)) | ||
| 1036 | (if count | ||
| 1037 | (setq count (prefix-numeric-value count)) | ||
| 1038 | (setq count python-indent-offset)) | ||
| 1039 | (indent-rigidly start end count))) | ||
| 1040 | |||
| 1041 | (defun python-indent-electric-colon (arg) | ||
| 1042 | "Insert a colon and maybe de-indent the current line. | ||
| 1043 | With numeric ARG, just insert that many colons. With | ||
| 1044 | \\[universal-argument], just insert a single colon." | ||
| 1045 | (interactive "*P") | ||
| 1046 | (self-insert-command (if (not (integerp arg)) 1 arg)) | ||
| 1047 | (when (and (not arg) | ||
| 1048 | (eolp) | ||
| 1049 | (not (equal ?: (char-after (- (point-marker) 2)))) | ||
| 1050 | (not (python-syntax-comment-or-string-p))) | ||
| 1051 | (let ((indentation (current-indentation)) | ||
| 1052 | (calculated-indentation (python-indent-calculate-indentation))) | ||
| 1053 | (python-info-closing-block-message) | ||
| 1054 | (when (> indentation calculated-indentation) | ||
| 1055 | (save-excursion | ||
| 1056 | (indent-line-to calculated-indentation) | ||
| 1057 | (when (not (python-info-closing-block-message)) | ||
| 1058 | (indent-line-to indentation))))))) | ||
| 1059 | (put 'python-indent-electric-colon 'delete-selection t) | ||
| 1060 | |||
| 1061 | (defun python-indent-post-self-insert-function () | ||
| 1062 | "Adjust closing paren line indentation after a char is added. | ||
| 1063 | This function is intended to be added to the | ||
| 1064 | `post-self-insert-hook.' If a line renders a paren alone, after | ||
| 1065 | adding a char before it, the line will be re-indented | ||
| 1066 | automatically if needed." | ||
| 1067 | (when (and (eq (char-before) last-command-event) | ||
| 1068 | (not (bolp)) | ||
| 1069 | (memq (char-after) '(?\) ?\] ?\}))) | ||
| 1070 | (save-excursion | ||
| 1071 | (goto-char (line-beginning-position)) | ||
| 1072 | ;; If after going to the beginning of line the point | ||
| 1073 | ;; is still inside a paren it's ok to do the trick | ||
| 1074 | (when (python-syntax-context 'paren) | ||
| 1075 | (let ((indentation (python-indent-calculate-indentation))) | ||
| 1076 | (when (< (current-indentation) indentation) | ||
| 1077 | (indent-line-to indentation))))))) | ||
| 1078 | |||
| 862 | 1079 | ||
| 863 | ;;;; Movement. | 1080 | ;;; Navigation |
| 864 | 1081 | ||
| 865 | ;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like | 1082 | (defvar python-nav-beginning-of-defun-regexp |
| 866 | ;; block, statement, depending on context. | 1083 | (python-rx line-start (* space) defun (+ space) (group symbol-name)) |
| 867 | 1084 | "Regexp matching class or function definition. | |
| 868 | (defun python-beginning-of-defun () | 1085 | The name of the defun should be grouped so it can be retrieved |
| 869 | "`beginning-of-defun-function' for Python. | 1086 | via `match-string'.") |
| 870 | Finds beginning of innermost nested class or method definition. | 1087 | |
| 871 | Returns the name of the definition found at the end, or nil if | 1088 | (defun python-nav--beginning-of-defun (&optional arg) |
| 872 | reached start of buffer." | 1089 | "Internal implementation of `python-nav-beginning-of-defun'. |
| 873 | (let ((ci (current-indentation)) | 1090 | With positive ARG search backwards, else search forwards." |
| 874 | (def-re (rx line-start (0+ space) (or "def" "class") (1+ space) | 1091 | (when (or (null arg) (= arg 0)) (setq arg 1)) |
| 875 | (group (1+ (or word (syntax symbol)))))) | 1092 | (let* ((re-search-fn (if (> arg 0) |
| 876 | found lep) ;; def-line | 1093 | #'re-search-backward |
| 877 | (if (python-comment-line-p) | 1094 | #'re-search-forward)) |
| 878 | (setq ci most-positive-fixnum)) | 1095 | (line-beg-pos (line-beginning-position)) |
| 879 | (while (and (not (bobp)) (not found)) | 1096 | (line-content-start (+ line-beg-pos (current-indentation))) |
| 880 | ;; Treat bol at beginning of function as outside function so | 1097 | (pos (point-marker)) |
| 881 | ;; that successive C-M-a makes progress backwards. | 1098 | (beg-indentation |
| 882 | ;;(setq def-line (looking-at def-re)) | 1099 | (and (> arg 0) |
| 883 | (unless (bolp) (end-of-line)) | 1100 | (save-excursion |
| 884 | (setq lep (line-end-position)) | 1101 | (and (python-info-current-line-empty-p) |
| 885 | (if (and (re-search-backward def-re nil 'move) | 1102 | (python-util-forward-comment -1)) |
| 886 | ;; Must be less indented or matching top level, or | 1103 | (python-nav-beginning-of-statement) |
| 887 | ;; equally indented if we started on a definition line. | 1104 | (if (python-info-looking-at-beginning-of-defun) |
| 888 | (let ((in (current-indentation))) | 1105 | (+ (current-indentation) python-indent-offset) |
| 889 | (or (and (zerop ci) (zerop in)) | 1106 | (current-indentation))))) |
| 890 | (= lep (line-end-position)) ; on initial line | 1107 | (found |
| 891 | ;; Not sure why it was like this -- fails in case of | 1108 | (progn |
| 892 | ;; last internal function followed by first | 1109 | (when (and (< arg 0) |
| 893 | ;; non-def statement of the main body. | 1110 | (python-info-looking-at-beginning-of-defun)) |
| 894 | ;; (and def-line (= in ci)) | 1111 | (end-of-line 1)) |
| 895 | (= in ci) | 1112 | (while (and (funcall re-search-fn |
| 896 | (< in ci))) | 1113 | python-nav-beginning-of-defun-regexp nil t) |
| 897 | (not (python-in-string/comment))) | 1114 | (or (python-syntax-context-type) |
| 898 | (setq found t))) | 1115 | ;; Handle nested defuns when moving |
| 1116 | ;; backwards by checking indentation. | ||
| 1117 | (and (> arg 0) | ||
| 1118 | (not (= (current-indentation) 0)) | ||
| 1119 | (>= (current-indentation) beg-indentation))))) | ||
| 1120 | (and (python-info-looking-at-beginning-of-defun) | ||
| 1121 | (or (not (= (line-number-at-pos pos) | ||
| 1122 | (line-number-at-pos))) | ||
| 1123 | (and (>= (point) line-beg-pos) | ||
| 1124 | (<= (point) line-content-start) | ||
| 1125 | (> pos line-content-start))))))) | ||
| 1126 | (if found | ||
| 1127 | (or (beginning-of-line 1) t) | ||
| 1128 | (and (goto-char pos) nil)))) | ||
| 1129 | |||
| 1130 | (defun python-nav-beginning-of-defun (&optional arg) | ||
| 1131 | "Move point to `beginning-of-defun'. | ||
| 1132 | With positive ARG search backwards else search forward. When ARG | ||
| 1133 | is nil or 0 defaults to 1. When searching backwards nested | ||
| 1134 | defuns are handled with care depending on current point | ||
| 1135 | position. Return non-nil if point is moved to | ||
| 1136 | `beginning-of-defun'." | ||
| 1137 | (when (or (null arg) (= arg 0)) (setq arg 1)) | ||
| 1138 | (let ((found)) | ||
| 1139 | (cond ((and (eq this-command 'mark-defun) | ||
| 1140 | (python-info-looking-at-beginning-of-defun))) | ||
| 1141 | (t | ||
| 1142 | (dotimes (i (if (> arg 0) arg (- arg))) | ||
| 1143 | (when (and (python-nav--beginning-of-defun arg) | ||
| 1144 | (not found)) | ||
| 1145 | (setq found t))))) | ||
| 899 | found)) | 1146 | found)) |
| 900 | 1147 | ||
| 901 | (defun python-end-of-defun () | 1148 | (defun python-nav-end-of-defun () |
| 902 | "`end-of-defun-function' for Python. | 1149 | "Move point to the end of def or class. |
| 903 | Finds end of innermost nested class or method definition." | 1150 | Returns nil if point is not in a def or class." |
| 904 | (let ((orig (point)) | 1151 | (interactive) |
| 905 | (pattern (rx line-start (0+ space) (or "def" "class") space))) | 1152 | (let ((beg-defun-indent) |
| 906 | ;; Go to start of current block and check whether it's at top | 1153 | (beg-pos (point))) |
| 907 | ;; level. If it is, and not a block start, look forward for | 1154 | (when (or (python-info-looking-at-beginning-of-defun) |
| 908 | ;; definition statement. | 1155 | (python-nav-beginning-of-defun 1) |
| 909 | (when (python-comment-line-p) | 1156 | (python-nav-beginning-of-defun -1)) |
| 910 | (end-of-line) | 1157 | (setq beg-defun-indent (current-indentation)) |
| 911 | (forward-comment most-positive-fixnum)) | 1158 | (while (progn |
| 912 | (if (not (python-open-block-statement-p)) | 1159 | (python-nav-end-of-statement) |
| 913 | (python-beginning-of-block)) | 1160 | (python-util-forward-comment 1) |
| 914 | (if (zerop (current-indentation)) | 1161 | (and (> (current-indentation) beg-defun-indent) |
| 915 | (unless (python-open-block-statement-p) | 1162 | (not (eobp))))) |
| 916 | (while (and (re-search-forward pattern nil 'move) | 1163 | (python-util-forward-comment -1) |
| 917 | (python-in-string/comment))) ; just loop | 1164 | (forward-line 1) |
| 918 | (unless (eobp) | 1165 | ;; Ensure point moves forward. |
| 919 | (beginning-of-line))) | 1166 | (and (> beg-pos (point)) (goto-char beg-pos))))) |
| 920 | ;; Don't move before top-level statement that would end defun. | 1167 | |
| 921 | (end-of-line) | 1168 | (defun python-nav-beginning-of-statement () |
| 922 | (python-beginning-of-defun)) | 1169 | "Move to start of current statement." |
| 923 | ;; If we got to the start of buffer, look forward for | 1170 | (interactive "^") |
| 924 | ;; definition statement. | 1171 | (while (and (or (back-to-indentation) t) |
| 925 | (if (and (bobp) (not (looking-at "def\\|class"))) | 1172 | (not (bobp)) |
| 926 | (while (and (not (eobp)) | 1173 | (when (or |
| 927 | (re-search-forward pattern nil 'move) | 1174 | (save-excursion |
| 928 | (python-in-string/comment)))) ; just loop | 1175 | (forward-line -1) |
| 929 | ;; We're at a definition statement (or end-of-buffer). | 1176 | (python-info-line-ends-backslash-p)) |
| 930 | (unless (eobp) | 1177 | (python-syntax-context 'string) |
| 931 | (python-end-of-block) | 1178 | (python-syntax-context 'paren)) |
| 932 | ;; Count trailing space in defun (but not trailing comments). | 1179 | (forward-line -1)))) |
| 933 | (skip-syntax-forward " >") | 1180 | (point-marker)) |
| 934 | (unless (eobp) ; e.g. missing final newline | 1181 | |
| 935 | (beginning-of-line))) | 1182 | (defun python-nav-end-of-statement () |
| 936 | ;; Catch pathological cases like this, where the beginning-of-defun | 1183 | "Move to end of current statement." |
| 937 | ;; skips to a definition we're not in: | 1184 | (interactive "^") |
| 938 | ;; if ...: | 1185 | (while (and (goto-char (line-end-position)) |
| 939 | ;; ... | 1186 | (not (eobp)) |
| 940 | ;; else: | 1187 | (when (or |
| 941 | ;; ... # point here | 1188 | (python-info-line-ends-backslash-p) |
| 942 | ;; ... | 1189 | (python-syntax-context 'string) |
| 943 | ;; def ... | 1190 | (python-syntax-context 'paren)) |
| 944 | (if (< (point) orig) | 1191 | (forward-line 1)))) |
| 945 | (goto-char (point-max))))) | 1192 | (point-marker)) |
| 946 | 1193 | ||
| 947 | (defun python-beginning-of-statement () | 1194 | (defun python-nav-backward-statement (&optional arg) |
| 948 | "Go to start of current statement. | 1195 | "Move backward to previous statement. |
| 949 | Accounts for continuation lines, multi-line strings, and | 1196 | With ARG, repeat. See `python-nav-forward-statement'." |
| 950 | multi-line bracketed expressions." | 1197 | (interactive "^p") |
| 951 | (while | 1198 | (or arg (setq arg 1)) |
| 952 | (if (python-backslash-continuation-line-p) | 1199 | (python-nav-forward-statement (- arg))) |
| 953 | (progn (forward-line -1) t) | 1200 | |
| 954 | (beginning-of-line) | 1201 | (defun python-nav-forward-statement (&optional arg) |
| 955 | (or (python-beginning-of-string) | 1202 | "Move forward to next statement. |
| 956 | (python-skip-out)))) | 1203 | With ARG, repeat. With negative argument, move ARG times |
| 957 | (back-to-indentation)) | 1204 | backward to previous statement." |
| 958 | 1205 | (interactive "^p") | |
| 959 | (defun python-skip-out (&optional forward syntax) | 1206 | (or arg (setq arg 1)) |
| 960 | "Skip out of any nested brackets. | 1207 | (while (> arg 0) |
| 961 | Skip forward if FORWARD is non-nil, else backward. | 1208 | (python-nav-end-of-statement) |
| 962 | If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point. | 1209 | (python-util-forward-comment) |
| 963 | Return non-nil if and only if skipping was done." | 1210 | (python-nav-beginning-of-statement) |
| 964 | ;; FIXME: Use syntax-ppss-toplevel-pos. | 1211 | (setq arg (1- arg))) |
| 965 | (let ((depth (syntax-ppss-depth (or syntax (syntax-ppss)))) | 1212 | (while (< arg 0) |
| 966 | (forward (if forward -1 1))) | 1213 | (python-nav-beginning-of-statement) |
| 967 | (unless (zerop depth) | 1214 | (python-util-forward-comment -1) |
| 968 | (if (> depth 0) | 1215 | (python-nav-beginning-of-statement) |
| 969 | ;; Skip forward out of nested brackets. | 1216 | (setq arg (1+ arg)))) |
| 970 | (condition-case () ; beware invalid syntax | 1217 | |
| 971 | (progn (backward-up-list (* forward depth)) t) | 1218 | (defun python-nav-beginning-of-block () |
| 972 | (error nil)) | 1219 | "Move to start of current block." |
| 973 | ;; Invalid syntax (too many closed brackets). | 1220 | (interactive "^") |
| 974 | ;; Skip out of as many as possible. | 1221 | (let ((starting-pos (point)) |
| 975 | (let (done) | 1222 | (block-regexp (python-rx |
| 976 | (while (condition-case () | 1223 | line-start (* whitespace) block-start))) |
| 977 | (progn (backward-up-list forward) | 1224 | (if (progn |
| 978 | (setq done t)) | 1225 | (python-nav-beginning-of-statement) |
| 979 | (error nil))) | 1226 | (looking-at (python-rx block-start))) |
| 980 | done))))) | 1227 | (point-marker) |
| 981 | 1228 | ;; Go to first line beginning a statement | |
| 982 | (defun python-end-of-statement () | 1229 | (while (and (not (bobp)) |
| 983 | "Go to the end of the current statement and return point. | 1230 | (or (and (python-nav-beginning-of-statement) nil) |
| 984 | Usually this is the start of the next line, but if this is a | 1231 | (python-info-current-line-comment-p) |
| 985 | multi-line statement we need to skip over the continuation lines. | 1232 | (python-info-current-line-empty-p))) |
| 986 | On a comment line, go to end of line." | 1233 | (forward-line -1)) |
| 987 | (end-of-line) | 1234 | (let ((block-matching-indent |
| 988 | (while (let (comment) | 1235 | (- (current-indentation) python-indent-offset))) |
| 989 | ;; Move past any enclosing strings and sexps, or stop if | 1236 | (while |
| 990 | ;; we're in a comment. | 1237 | (and (python-nav-backward-block) |
| 991 | (while (let ((s (syntax-ppss))) | 1238 | (> (current-indentation) block-matching-indent))) |
| 992 | (cond ((eq 'comment (syntax-ppss-context s)) | 1239 | (if (and (looking-at (python-rx block-start)) |
| 993 | (setq comment t) | 1240 | (= (current-indentation) block-matching-indent)) |
| 994 | nil) | 1241 | (point-marker) |
| 995 | ((eq 'string (syntax-ppss-context s)) | 1242 | (and (goto-char starting-pos) nil)))))) |
| 996 | ;; Go to start of string and skip it. | 1243 | |
| 997 | (let ((pos (point))) | 1244 | (defun python-nav-end-of-block () |
| 998 | (goto-char (nth 8 s)) | 1245 | "Move to end of current block." |
| 999 | (condition-case () ; beware invalid syntax | 1246 | (interactive "^") |
| 1000 | (progn (forward-sexp) t) | 1247 | (when (python-nav-beginning-of-block) |
| 1001 | ;; If there's a mismatched string, make sure | 1248 | (let ((block-indentation (current-indentation))) |
| 1002 | ;; we still overall move *forward*. | 1249 | (python-nav-end-of-statement) |
| 1003 | (error (goto-char pos) (end-of-line))))) | 1250 | (while (and (forward-line 1) |
| 1004 | ((python-skip-out t s)))) | 1251 | (not (eobp)) |
| 1005 | (end-of-line)) | 1252 | (or (and (> (current-indentation) block-indentation) |
| 1006 | (unless comment | 1253 | (or (python-nav-end-of-statement) t)) |
| 1007 | (eq ?\\ (char-before)))) ; Line continued? | 1254 | (python-info-current-line-comment-p) |
| 1008 | (end-of-line 2)) ; Try next line. | 1255 | (python-info-current-line-empty-p)))) |
| 1009 | (point)) | 1256 | (python-util-forward-comment -1) |
| 1010 | 1257 | (point-marker)))) | |
| 1011 | (defun python-previous-statement (&optional count) | 1258 | |
| 1012 | "Go to start of previous statement. | 1259 | (defun python-nav-backward-block (&optional arg) |
| 1013 | With argument COUNT, do it COUNT times. Stop at beginning of buffer. | 1260 | "Move backward to previous block of code. |
| 1014 | Return count of statements left to move." | 1261 | With ARG, repeat. See `python-nav-forward-block'." |
| 1015 | (interactive "p") | 1262 | (interactive "^p") |
| 1016 | (unless count (setq count 1)) | 1263 | (or arg (setq arg 1)) |
| 1017 | (if (< count 0) | 1264 | (python-nav-forward-block (- arg))) |
| 1018 | (python-next-statement (- count)) | 1265 | |
| 1019 | (python-beginning-of-statement) | 1266 | (defun python-nav-forward-block (&optional arg) |
| 1020 | (while (and (> count 0) (not (bobp))) | 1267 | "Move forward to next block of code. |
| 1021 | (python-skip-comments/blanks t) | 1268 | With ARG, repeat. With negative argument, move ARG times |
| 1022 | (python-beginning-of-statement) | 1269 | backward to previous block." |
| 1023 | (unless (bobp) (setq count (1- count)))) | 1270 | (interactive "^p") |
| 1024 | count)) | 1271 | (or arg (setq arg 1)) |
| 1025 | 1272 | (let ((block-start-regexp | |
| 1026 | (defun python-next-statement (&optional count) | 1273 | (python-rx line-start (* whitespace) block-start)) |
| 1027 | "Go to start of next statement. | 1274 | (starting-pos (point))) |
| 1028 | With argument COUNT, do it COUNT times. Stop at end of buffer. | 1275 | (while (> arg 0) |
| 1029 | Return count of statements left to move." | 1276 | (python-nav-end-of-statement) |
| 1030 | (interactive "p") | 1277 | (while (and |
| 1031 | (unless count (setq count 1)) | 1278 | (re-search-forward block-start-regexp nil t) |
| 1032 | (if (< count 0) | 1279 | (python-syntax-context-type))) |
| 1033 | (python-previous-statement (- count)) | ||
| 1034 | (beginning-of-line) | ||
| 1035 | (let (bogus) | ||
| 1036 | (while (and (> count 0) (not (eobp)) (not bogus)) | ||
| 1037 | (python-end-of-statement) | ||
| 1038 | (python-skip-comments/blanks) | ||
| 1039 | (if (eq 'string (syntax-ppss-context (syntax-ppss))) | ||
| 1040 | (setq bogus t) | ||
| 1041 | (unless (eobp) | ||
| 1042 | (setq count (1- count)))))) | ||
| 1043 | count)) | ||
| 1044 | |||
| 1045 | (defun python-beginning-of-block (&optional arg) | ||
| 1046 | "Go to start of current block. | ||
| 1047 | With numeric arg, do it that many times. If ARG is negative, call | ||
| 1048 | `python-end-of-block' instead. | ||
| 1049 | If point is on the first line of a block, use its outer block. | ||
| 1050 | If current statement is in column zero, don't move and return nil. | ||
| 1051 | Otherwise return non-nil." | ||
| 1052 | (interactive "p") | ||
| 1053 | (unless arg (setq arg 1)) | ||
| 1054 | (cond | ||
| 1055 | ((zerop arg)) | ||
| 1056 | ((< arg 0) (python-end-of-block (- arg))) | ||
| 1057 | (t | ||
| 1058 | (let ((point (point))) | ||
| 1059 | (if (or (python-comment-line-p) | ||
| 1060 | (python-blank-line-p)) | ||
| 1061 | (python-skip-comments/blanks t)) | ||
| 1062 | (python-beginning-of-statement) | ||
| 1063 | (let ((ci (current-indentation))) | ||
| 1064 | (if (zerop ci) | ||
| 1065 | (not (goto-char point)) ; return nil | ||
| 1066 | ;; Look upwards for less indented statement. | ||
| 1067 | (if (catch 'done | ||
| 1068 | ;;; This is slower than the below. | ||
| 1069 | ;;; (while (zerop (python-previous-statement)) | ||
| 1070 | ;;; (when (and (< (current-indentation) ci) | ||
| 1071 | ;;; (python-open-block-statement-p t)) | ||
| 1072 | ;;; (beginning-of-line) | ||
| 1073 | ;;; (throw 'done t))) | ||
| 1074 | (while (and (zerop (forward-line -1))) | ||
| 1075 | (when (and (< (current-indentation) ci) | ||
| 1076 | (not (python-comment-line-p)) | ||
| 1077 | ;; Move to beginning to save effort in case | ||
| 1078 | ;; this is in string. | ||
| 1079 | (progn (python-beginning-of-statement) t) | ||
| 1080 | (python-open-block-statement-p t)) | ||
| 1081 | (beginning-of-line) | ||
| 1082 | (throw 'done t))) | ||
| 1083 | (not (goto-char point))) ; Failed -- return nil | ||
| 1084 | (python-beginning-of-block (1- arg))))))))) | ||
| 1085 | |||
| 1086 | (defun python-end-of-block (&optional arg) | ||
| 1087 | "Go to end of current block. | ||
| 1088 | With numeric arg, do it that many times. If ARG is negative, | ||
| 1089 | call `python-beginning-of-block' instead. | ||
| 1090 | If current statement is in column zero and doesn't open a block, | ||
| 1091 | don't move and return nil. Otherwise return t." | ||
| 1092 | (interactive "p") | ||
| 1093 | (unless arg (setq arg 1)) | ||
| 1094 | (if (< arg 0) | ||
| 1095 | (python-beginning-of-block (- arg)) | ||
| 1096 | (while (and (> arg 0) | ||
| 1097 | (let* ((point (point)) | ||
| 1098 | (_ (if (python-comment-line-p) | ||
| 1099 | (python-skip-comments/blanks t))) | ||
| 1100 | (ci (current-indentation)) | ||
| 1101 | (open (python-open-block-statement-p))) | ||
| 1102 | (if (and (zerop ci) (not open)) | ||
| 1103 | (not (goto-char point)) | ||
| 1104 | (catch 'done | ||
| 1105 | (while (zerop (python-next-statement)) | ||
| 1106 | (when (or (and open (<= (current-indentation) ci)) | ||
| 1107 | (< (current-indentation) ci)) | ||
| 1108 | (python-skip-comments/blanks t) | ||
| 1109 | (beginning-of-line 2) | ||
| 1110 | (throw 'done t))))))) | ||
| 1111 | (setq arg (1- arg))) | 1280 | (setq arg (1- arg))) |
| 1112 | (zerop arg))) | 1281 | (while (< arg 0) |
| 1282 | (python-nav-beginning-of-statement) | ||
| 1283 | (while (and | ||
| 1284 | (re-search-backward block-start-regexp nil t) | ||
| 1285 | (python-syntax-context-type))) | ||
| 1286 | (setq arg (1+ arg))) | ||
| 1287 | (python-nav-beginning-of-statement) | ||
| 1288 | (if (not (looking-at (python-rx block-start))) | ||
| 1289 | (and (goto-char starting-pos) nil) | ||
| 1290 | (and (not (= (point) starting-pos)) (point-marker))))) | ||
| 1291 | |||
| 1292 | (defun python-nav-lisp-forward-sexp-safe (&optional arg) | ||
| 1293 | "Safe version of standard `forward-sexp'. | ||
| 1294 | When ARG > 0 move forward, else if ARG is < 0." | ||
| 1295 | (or arg (setq arg 1)) | ||
| 1296 | (let ((forward-sexp-function nil) | ||
| 1297 | (paren-regexp | ||
| 1298 | (if (> arg 0) (python-rx close-paren) (python-rx open-paren))) | ||
| 1299 | (search-fn | ||
| 1300 | (if (> arg 0) #'re-search-forward #'re-search-backward))) | ||
| 1301 | (condition-case nil | ||
| 1302 | (forward-sexp arg) | ||
| 1303 | (error | ||
| 1304 | (while (and (funcall search-fn paren-regexp nil t) | ||
| 1305 | (python-syntax-context 'paren))))))) | ||
| 1306 | |||
| 1307 | (defun python-nav--forward-sexp (&optional dir) | ||
| 1308 | "Move to forward sexp. | ||
| 1309 | With positive Optional argument DIR direction move forward, else | ||
| 1310 | backwards." | ||
| 1311 | (setq dir (or dir 1)) | ||
| 1312 | (unless (= dir 0) | ||
| 1313 | (let* ((forward-p (if (> dir 0) | ||
| 1314 | (and (setq dir 1) t) | ||
| 1315 | (and (setq dir -1) nil))) | ||
| 1316 | (re-search-fn (if forward-p | ||
| 1317 | 're-search-forward | ||
| 1318 | 're-search-backward)) | ||
| 1319 | (context-type (python-syntax-context-type))) | ||
| 1320 | (cond | ||
| 1321 | ((eq context-type 'string) | ||
| 1322 | ;; Inside of a string, get out of it. | ||
| 1323 | (while (and (funcall re-search-fn "[\"']" nil t) | ||
| 1324 | (python-syntax-context 'string)))) | ||
| 1325 | ((eq context-type 'comment) | ||
| 1326 | ;; Inside of a comment, just move forward. | ||
| 1327 | (python-util-forward-comment dir)) | ||
| 1328 | ((or (eq context-type 'paren) | ||
| 1329 | (and forward-p (looking-at (python-rx open-paren))) | ||
| 1330 | (and (not forward-p) | ||
| 1331 | (eq (syntax-class (syntax-after (1- (point)))) | ||
| 1332 | (car (string-to-syntax ")"))))) | ||
| 1333 | ;; Inside a paren or looking at it, lisp knows what to do. | ||
| 1334 | (python-nav-lisp-forward-sexp-safe dir)) | ||
| 1335 | (t | ||
| 1336 | ;; This part handles the lispy feel of | ||
| 1337 | ;; `python-nav-forward-sexp'. Knowing everything about the | ||
| 1338 | ;; current context and the context of the next sexp tries to | ||
| 1339 | ;; follow the lisp sexp motion commands in a symmetric manner. | ||
| 1340 | (let* ((context | ||
| 1341 | (cond | ||
| 1342 | ((python-info-beginning-of-block-p) 'block-start) | ||
| 1343 | ((python-info-end-of-block-p) 'block-end) | ||
| 1344 | ((python-info-beginning-of-statement-p) 'statement-start) | ||
| 1345 | ((python-info-end-of-statement-p) 'statement-end))) | ||
| 1346 | (next-sexp-pos | ||
| 1347 | (save-excursion | ||
| 1348 | (python-nav-lisp-forward-sexp-safe dir) | ||
| 1349 | (point))) | ||
| 1350 | (next-sexp-context | ||
| 1351 | (save-excursion | ||
| 1352 | (goto-char next-sexp-pos) | ||
| 1353 | (cond | ||
| 1354 | ((python-info-beginning-of-block-p) 'block-start) | ||
| 1355 | ((python-info-end-of-block-p) 'block-end) | ||
| 1356 | ((python-info-beginning-of-statement-p) 'statement-start) | ||
| 1357 | ((python-info-end-of-statement-p) 'statement-end) | ||
| 1358 | ((python-info-statement-starts-block-p) 'starts-block) | ||
| 1359 | ((python-info-statement-ends-block-p) 'ends-block))))) | ||
| 1360 | (if forward-p | ||
| 1361 | (cond ((and (not (eobp)) | ||
| 1362 | (python-info-current-line-empty-p)) | ||
| 1363 | (python-util-forward-comment dir) | ||
| 1364 | (python-nav--forward-sexp dir)) | ||
| 1365 | ((eq context 'block-start) | ||
| 1366 | (python-nav-end-of-block)) | ||
| 1367 | ((eq context 'statement-start) | ||
| 1368 | (python-nav-end-of-statement)) | ||
| 1369 | ((and (memq context '(statement-end block-end)) | ||
| 1370 | (eq next-sexp-context 'ends-block)) | ||
| 1371 | (goto-char next-sexp-pos) | ||
| 1372 | (python-nav-end-of-block)) | ||
| 1373 | ((and (memq context '(statement-end block-end)) | ||
| 1374 | (eq next-sexp-context 'starts-block)) | ||
| 1375 | (goto-char next-sexp-pos) | ||
| 1376 | (python-nav-end-of-block)) | ||
| 1377 | ((memq context '(statement-end block-end)) | ||
| 1378 | (goto-char next-sexp-pos) | ||
| 1379 | (python-nav-end-of-statement)) | ||
| 1380 | (t (goto-char next-sexp-pos))) | ||
| 1381 | (cond ((and (not (bobp)) | ||
| 1382 | (python-info-current-line-empty-p)) | ||
| 1383 | (python-util-forward-comment dir) | ||
| 1384 | (python-nav--forward-sexp dir)) | ||
| 1385 | ((eq context 'block-end) | ||
| 1386 | (python-nav-beginning-of-block)) | ||
| 1387 | ((eq context 'statement-end) | ||
| 1388 | (python-nav-beginning-of-statement)) | ||
| 1389 | ((and (memq context '(statement-start block-start)) | ||
| 1390 | (eq next-sexp-context 'starts-block)) | ||
| 1391 | (goto-char next-sexp-pos) | ||
| 1392 | (python-nav-beginning-of-block)) | ||
| 1393 | ((and (memq context '(statement-start block-start)) | ||
| 1394 | (eq next-sexp-context 'ends-block)) | ||
| 1395 | (goto-char next-sexp-pos) | ||
| 1396 | (python-nav-beginning-of-block)) | ||
| 1397 | ((memq context '(statement-start block-start)) | ||
| 1398 | (goto-char next-sexp-pos) | ||
| 1399 | (python-nav-beginning-of-statement)) | ||
| 1400 | (t (goto-char next-sexp-pos)))))))))) | ||
| 1401 | |||
| 1402 | (defun python-nav--backward-sexp () | ||
| 1403 | "Move to backward sexp." | ||
| 1404 | (python-nav--forward-sexp -1)) | ||
| 1405 | |||
| 1406 | (defun python-nav-forward-sexp (&optional arg) | ||
| 1407 | "Move forward across one block of code. | ||
| 1408 | With ARG, do it that many times. Negative arg -N means | ||
| 1409 | move backward N times." | ||
| 1410 | (interactive "^p") | ||
| 1411 | (or arg (setq arg 1)) | ||
| 1412 | (while (> arg 0) | ||
| 1413 | (python-nav--forward-sexp) | ||
| 1414 | (setq arg (1- arg))) | ||
| 1415 | (while (< arg 0) | ||
| 1416 | (python-nav--backward-sexp) | ||
| 1417 | (setq arg (1+ arg)))) | ||
| 1418 | |||
| 1419 | (defun python-nav--up-list (&optional dir) | ||
| 1420 | "Internal implementation of `python-nav-up-list'. | ||
| 1421 | DIR is always 1 or -1 and comes sanitized from | ||
| 1422 | `python-nav-up-list' calls." | ||
| 1423 | (let ((context (python-syntax-context-type)) | ||
| 1424 | (forward-p (> dir 0))) | ||
| 1425 | (cond | ||
| 1426 | ((memq context '(string comment))) | ||
| 1427 | ((eq context 'paren) | ||
| 1428 | (let ((forward-sexp-function)) | ||
| 1429 | (up-list dir))) | ||
| 1430 | ((and forward-p (python-info-end-of-block-p)) | ||
| 1431 | (let ((parent-end-pos | ||
| 1432 | (save-excursion | ||
| 1433 | (let ((indentation (and | ||
| 1434 | (python-nav-beginning-of-block) | ||
| 1435 | (current-indentation)))) | ||
| 1436 | (while (and indentation | ||
| 1437 | (> indentation 0) | ||
| 1438 | (>= (current-indentation) indentation) | ||
| 1439 | (python-nav-backward-block))) | ||
| 1440 | (python-nav-end-of-block))))) | ||
| 1441 | (and (> (or parent-end-pos (point)) (point)) | ||
| 1442 | (goto-char parent-end-pos)))) | ||
| 1443 | (forward-p (python-nav-end-of-block)) | ||
| 1444 | ((and (not forward-p) | ||
| 1445 | (> (current-indentation) 0) | ||
| 1446 | (python-info-beginning-of-block-p)) | ||
| 1447 | (let ((prev-block-pos | ||
| 1448 | (save-excursion | ||
| 1449 | (let ((indentation (current-indentation))) | ||
| 1450 | (while (and (python-nav-backward-block) | ||
| 1451 | (>= (current-indentation) indentation)))) | ||
| 1452 | (point)))) | ||
| 1453 | (and (> (point) prev-block-pos) | ||
| 1454 | (goto-char prev-block-pos)))) | ||
| 1455 | ((not forward-p) (python-nav-beginning-of-block))))) | ||
| 1456 | |||
| 1457 | (defun python-nav-up-list (&optional arg) | ||
| 1458 | "Move forward out of one level of parentheses (or blocks). | ||
| 1459 | With ARG, do this that many times. | ||
| 1460 | A negative argument means move backward but still to a less deep spot. | ||
| 1461 | This command assumes point is not in a string or comment." | ||
| 1462 | (interactive "^p") | ||
| 1463 | (or arg (setq arg 1)) | ||
| 1464 | (while (> arg 0) | ||
| 1465 | (python-nav--up-list 1) | ||
| 1466 | (setq arg (1- arg))) | ||
| 1467 | (while (< arg 0) | ||
| 1468 | (python-nav--up-list -1) | ||
| 1469 | (setq arg (1+ arg)))) | ||
| 1470 | |||
| 1471 | (defun python-nav-backward-up-list (&optional arg) | ||
| 1472 | "Move backward out of one level of parentheses (or blocks). | ||
| 1473 | With ARG, do this that many times. | ||
| 1474 | A negative argument means move backward but still to a less deep spot. | ||
| 1475 | This command assumes point is not in a string or comment." | ||
| 1476 | (interactive "^p") | ||
| 1477 | (or arg (setq arg 1)) | ||
| 1478 | (python-nav-up-list (- arg))) | ||
| 1113 | 1479 | ||
| 1114 | (defvar python-which-func-length-limit 40 | 1480 | |
| 1115 | "Non-strict length limit for `python-which-func' output.") | 1481 | ;;; Shell integration |
| 1116 | 1482 | ||
| 1117 | (defun python-which-func () | 1483 | (defcustom python-shell-buffer-name "Python" |
| 1118 | (let ((function-name (python-current-defun python-which-func-length-limit))) | 1484 | "Default buffer name for Python interpreter." |
| 1119 | (set-text-properties 0 (length function-name) nil function-name) | 1485 | :type 'string |
| 1120 | function-name)) | 1486 | :group 'python |
| 1487 | :safe 'stringp) | ||
| 1121 | 1488 | ||
| 1122 | 1489 | (defcustom python-shell-interpreter "python" | |
| 1123 | ;;;; Imenu. | 1490 | "Default Python interpreter for shell." |
| 1124 | 1491 | :type 'string | |
| 1125 | ;; For possibly speeding this up, here's the top of the ELP profile | 1492 | :group 'python) |
| 1126 | ;; for rescanning pydoc.py (2.2k lines, 90kb): | ||
| 1127 | ;; Function Name Call Count Elapsed Time Average Time | ||
| 1128 | ;; ==================================== ========== ============= ============ | ||
| 1129 | ;; python-imenu-create-index 156 2.430906 0.0155827307 | ||
| 1130 | ;; python-end-of-defun 155 1.2718260000 0.0082053290 | ||
| 1131 | ;; python-end-of-block 155 1.1898689999 0.0076765741 | ||
| 1132 | ;; python-next-statement 2970 1.024717 0.0003450225 | ||
| 1133 | ;; python-end-of-statement 2970 0.4332190000 0.0001458649 | ||
| 1134 | ;; python-beginning-of-defun 265 0.0918479999 0.0003465962 | ||
| 1135 | ;; python-skip-comments/blanks 3125 0.0753319999 2.410...e-05 | ||
| 1136 | |||
| 1137 | (defvar python-recursing) | ||
| 1138 | (defun python-imenu-create-index () | ||
| 1139 | "`imenu-create-index-function' for Python. | ||
| 1140 | |||
| 1141 | Makes nested Imenu menus from nested `class' and `def' statements. | ||
| 1142 | The nested menus are headed by an item referencing the outer | ||
| 1143 | definition; it has a space prepended to the name so that it sorts | ||
| 1144 | first with `imenu--sort-by-name' (though, unfortunately, sub-menus | ||
| 1145 | precede it)." | ||
| 1146 | (unless (boundp 'python-recursing) ; dynamically bound below | ||
| 1147 | ;; Normal call from Imenu. | ||
| 1148 | (goto-char (point-min)) | ||
| 1149 | ;; Without this, we can get an infloop if the buffer isn't all | ||
| 1150 | ;; fontified. I guess this is really a bug in syntax.el. OTOH, | ||
| 1151 | ;; _with_ this, imenu doesn't immediately work; I can't figure out | ||
| 1152 | ;; what's going on, but it must be something to do with timers in | ||
| 1153 | ;; font-lock. | ||
| 1154 | ;; This can't be right, especially not when jit-lock is not used. --Stef | ||
| 1155 | ;; (unless (get-text-property (1- (point-max)) 'fontified) | ||
| 1156 | ;; (font-lock-fontify-region (point-min) (point-max))) | ||
| 1157 | ) | ||
| 1158 | (let (index-alist) ; accumulated value to return | ||
| 1159 | (while (re-search-forward | ||
| 1160 | (rx line-start (0+ space) ; leading space | ||
| 1161 | (or (group "def") (group "class")) ; type | ||
| 1162 | (1+ space) (group (1+ (or word ?_)))) ; name | ||
| 1163 | nil t) | ||
| 1164 | (unless (python-in-string/comment) | ||
| 1165 | (let ((pos (match-beginning 0)) | ||
| 1166 | (name (match-string-no-properties 3))) | ||
| 1167 | (if (match-beginning 2) ; def or class? | ||
| 1168 | (setq name (concat "class " name))) | ||
| 1169 | (save-restriction | ||
| 1170 | (narrow-to-defun) | ||
| 1171 | (let* ((python-recursing t) | ||
| 1172 | (sublist (python-imenu-create-index))) | ||
| 1173 | (if sublist | ||
| 1174 | (progn (push (cons (concat " " name) pos) sublist) | ||
| 1175 | (push (cons name sublist) index-alist)) | ||
| 1176 | (push (cons name pos) index-alist))))))) | ||
| 1177 | (unless (boundp 'python-recursing) | ||
| 1178 | ;; Look for module variables. | ||
| 1179 | (let (vars) | ||
| 1180 | (goto-char (point-min)) | ||
| 1181 | (while (re-search-forward | ||
| 1182 | (rx line-start (group (1+ (or word ?_))) (0+ space) "=") | ||
| 1183 | nil t) | ||
| 1184 | (unless (python-in-string/comment) | ||
| 1185 | (push (cons (match-string 1) (match-beginning 1)) | ||
| 1186 | vars))) | ||
| 1187 | (setq index-alist (nreverse index-alist)) | ||
| 1188 | (if vars | ||
| 1189 | (push (cons "Module variables" | ||
| 1190 | (nreverse vars)) | ||
| 1191 | index-alist)))) | ||
| 1192 | index-alist)) | ||
| 1193 | |||
| 1194 | ;;;; `Electric' commands. | ||
| 1195 | 1493 | ||
| 1196 | (defun python-electric-colon (arg) | 1494 | (defcustom python-shell-internal-buffer-name "Python Internal" |
| 1197 | "Insert a colon and maybe outdent the line if it is a statement like `else'. | 1495 | "Default buffer name for the Internal Python interpreter." |
| 1198 | With numeric ARG, just insert that many colons. With \\[universal-argument], | 1496 | :type 'string |
| 1199 | just insert a single colon." | 1497 | :group 'python |
| 1200 | (interactive "*P") | 1498 | :safe 'stringp) |
| 1201 | (self-insert-command (if (not (integerp arg)) 1 arg)) | ||
| 1202 | (and (not arg) | ||
| 1203 | (eolp) | ||
| 1204 | (python-outdent-p) | ||
| 1205 | (not (python-in-string/comment)) | ||
| 1206 | (> (current-indentation) (python-calculate-indentation)) | ||
| 1207 | (python-indent-line))) ; OK, do it | ||
| 1208 | (put 'python-electric-colon 'delete-selection t) | ||
| 1209 | |||
| 1210 | (defun python-backspace (arg) | ||
| 1211 | "Maybe delete a level of indentation on the current line. | ||
| 1212 | Do so if point is at the end of the line's indentation outside | ||
| 1213 | strings and comments. | ||
| 1214 | Otherwise just call `backward-delete-char-untabify'. | ||
| 1215 | Repeat ARG times." | ||
| 1216 | (interactive "*p") | ||
| 1217 | (if (or (/= (current-indentation) (current-column)) | ||
| 1218 | (bolp) | ||
| 1219 | (python-continuation-line-p) | ||
| 1220 | (python-in-string/comment)) | ||
| 1221 | (backward-delete-char-untabify arg) | ||
| 1222 | ;; Look for the largest valid indentation which is smaller than | ||
| 1223 | ;; the current indentation. | ||
| 1224 | (let ((indent 0) | ||
| 1225 | (ci (current-indentation)) | ||
| 1226 | (indents (python-indentation-levels)) | ||
| 1227 | initial) | ||
| 1228 | (dolist (x indents) | ||
| 1229 | (if (< (car x) ci) | ||
| 1230 | (setq indent (max indent (car x))))) | ||
| 1231 | (setq initial (cdr (assq indent indents))) | ||
| 1232 | (if (> (length initial) 0) | ||
| 1233 | (message "Closes %s" initial)) | ||
| 1234 | (delete-horizontal-space) | ||
| 1235 | (indent-to indent)))) | ||
| 1236 | (put 'python-backspace 'delete-selection 'supersede) | ||
| 1237 | |||
| 1238 | ;;;; pychecker | ||
| 1239 | 1499 | ||
| 1240 | (defcustom python-check-command "pychecker --stdlib" | 1500 | (defcustom python-shell-interpreter-args "-i" |
| 1241 | "Command used to check a Python file." | 1501 | "Default arguments for the Python interpreter." |
| 1242 | :type 'string | 1502 | :type 'string |
| 1243 | :group 'python) | 1503 | :group 'python) |
| 1244 | 1504 | ||
| 1245 | (defvar python-saved-check-command nil | 1505 | (defcustom python-shell-prompt-regexp ">>> " |
| 1246 | "Internal use.") | 1506 | "Regular Expression matching top\-level input prompt of python shell. |
| 1507 | It should not contain a caret (^) at the beginning." | ||
| 1508 | :type 'string | ||
| 1509 | :group 'python | ||
| 1510 | :safe 'stringp) | ||
| 1247 | 1511 | ||
| 1248 | ;; After `sgml-validate-command'. | 1512 | (defcustom python-shell-prompt-block-regexp "[.][.][.] " |
| 1249 | (defun python-check (command) | 1513 | "Regular Expression matching block input prompt of python shell. |
| 1250 | "Check a Python file (default current buffer's file). | 1514 | It should not contain a caret (^) at the beginning." |
| 1251 | Runs COMMAND, a shell command, as if by `compile'. | 1515 | :type 'string |
| 1252 | See `python-check-command' for the default." | 1516 | :group 'python |
| 1253 | (interactive | 1517 | :safe 'stringp) |
| 1254 | (list (read-string "Checker command: " | 1518 | |
| 1255 | (or python-saved-check-command | 1519 | (defcustom python-shell-prompt-output-regexp "" |
| 1256 | (concat python-check-command " " | 1520 | "Regular Expression matching output prompt of python shell. |
| 1257 | (let ((name (buffer-file-name))) | 1521 | It should not contain a caret (^) at the beginning." |
| 1258 | (if name | 1522 | :type 'string |
| 1259 | (file-name-nondirectory name)))))))) | 1523 | :group 'python |
| 1260 | (set (make-local-variable 'python-saved-check-command) command) | 1524 | :safe 'stringp) |
| 1261 | (require 'compile) ;To define compilation-* variables. | ||
| 1262 | (save-some-buffers (not compilation-ask-about-save) nil) | ||
| 1263 | (let ((compilation-error-regexp-alist | ||
| 1264 | (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2) | ||
| 1265 | compilation-error-regexp-alist))) | ||
| 1266 | (compilation-start command))) | ||
| 1267 | |||
| 1268 | ;;;; Inferior mode stuff (following cmuscheme). | ||
| 1269 | 1525 | ||
| 1270 | (defcustom python-python-command "python" | 1526 | (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ " |
| 1271 | "Shell command to run Python interpreter. | 1527 | "Regular Expression matching pdb input prompt of python shell. |
| 1272 | Any arguments can't contain whitespace." | 1528 | It should not contain a caret (^) at the beginning." |
| 1529 | :type 'string | ||
| 1273 | :group 'python | 1530 | :group 'python |
| 1274 | :type 'string) | 1531 | :safe 'stringp) |
| 1275 | 1532 | ||
| 1276 | (defcustom python-jython-command "jython" | 1533 | (defcustom python-shell-enable-font-lock t |
| 1277 | "Shell command to run Jython interpreter. | 1534 | "Should syntax highlighting be enabled in the python shell buffer? |
| 1278 | Any arguments can't contain whitespace." | 1535 | Restart the python shell after changing this variable for it to take effect." |
| 1536 | :type 'boolean | ||
| 1537 | :group 'python | ||
| 1538 | :safe 'booleanp) | ||
| 1539 | |||
| 1540 | (defcustom python-shell-process-environment nil | ||
| 1541 | "List of environment variables for Python shell. | ||
| 1542 | This variable follows the same rules as `process-environment' | ||
| 1543 | since it merges with it before the process creation routines are | ||
| 1544 | called. When this variable is nil, the Python shell is run with | ||
| 1545 | the default `process-environment'." | ||
| 1546 | :type '(repeat string) | ||
| 1547 | :group 'python | ||
| 1548 | :safe 'listp) | ||
| 1549 | |||
| 1550 | (defcustom python-shell-extra-pythonpaths nil | ||
| 1551 | "List of extra pythonpaths for Python shell. | ||
| 1552 | The values of this variable are added to the existing value of | ||
| 1553 | PYTHONPATH in the `process-environment' variable." | ||
| 1554 | :type '(repeat string) | ||
| 1555 | :group 'python | ||
| 1556 | :safe 'listp) | ||
| 1557 | |||
| 1558 | (defcustom python-shell-exec-path nil | ||
| 1559 | "List of path to search for binaries. | ||
| 1560 | This variable follows the same rules as `exec-path' since it | ||
| 1561 | merges with it before the process creation routines are called. | ||
| 1562 | When this variable is nil, the Python shell is run with the | ||
| 1563 | default `exec-path'." | ||
| 1564 | :type '(repeat string) | ||
| 1565 | :group 'python | ||
| 1566 | :safe 'listp) | ||
| 1567 | |||
| 1568 | (defcustom python-shell-virtualenv-path nil | ||
| 1569 | "Path to virtualenv root. | ||
| 1570 | This variable, when set to a string, makes the values stored in | ||
| 1571 | `python-shell-process-environment' and `python-shell-exec-path' | ||
| 1572 | to be modified properly so shells are started with the specified | ||
| 1573 | virtualenv." | ||
| 1574 | :type 'string | ||
| 1279 | :group 'python | 1575 | :group 'python |
| 1280 | :type 'string) | 1576 | :safe 'stringp) |
| 1281 | 1577 | ||
| 1282 | (defvar python-command python-python-command | 1578 | (defcustom python-shell-setup-codes '(python-shell-completion-setup-code |
| 1283 | "Actual command used to run Python. | 1579 | python-ffap-setup-code |
| 1284 | May be `python-python-command' or `python-jython-command', possibly | 1580 | python-eldoc-setup-code) |
| 1285 | modified by the user. Additional arguments are added when the command | 1581 | "List of code run by `python-shell-send-setup-codes'." |
| 1286 | is used by `run-python' et al.") | 1582 | :type '(repeat symbol) |
| 1287 | 1583 | :group 'python | |
| 1288 | (defvar python-buffer nil | 1584 | :safe 'listp) |
| 1289 | "*The current Python process buffer. | 1585 | |
| 1290 | 1586 | (defcustom python-shell-compilation-regexp-alist | |
| 1291 | Commands that send text from source buffers to Python processes have | ||
| 1292 | to choose a process to send to. This is determined by buffer-local | ||
| 1293 | value of `python-buffer'. If its value in the current buffer, | ||
| 1294 | i.e. both any local value and the default one, is nil, `run-python' | ||
| 1295 | and commands that send to the Python process will start a new process. | ||
| 1296 | |||
| 1297 | Whenever \\[run-python] starts a new process, it resets the default | ||
| 1298 | value of `python-buffer' to be the new process's buffer and sets the | ||
| 1299 | buffer-local value similarly if the current buffer is in Python mode | ||
| 1300 | or Inferior Python mode, so that source buffer stays associated with a | ||
| 1301 | specific sub-process. | ||
| 1302 | |||
| 1303 | Use \\[python-set-proc] to set the default value from a buffer with a | ||
| 1304 | local value.") | ||
| 1305 | (make-variable-buffer-local 'python-buffer) | ||
| 1306 | |||
| 1307 | (defconst python-compilation-regexp-alist | ||
| 1308 | ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist. | ||
| 1309 | ;; The first already is (for CAML), but the second isn't. Anyhow, | ||
| 1310 | ;; these are specific to the inferior buffer. -- fx | ||
| 1311 | `((,(rx line-start (1+ (any " \t")) "File \"" | 1587 | `((,(rx line-start (1+ (any " \t")) "File \"" |
| 1312 | (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c | 1588 | (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c |
| 1313 | "\", line " (group (1+ digit))) | 1589 | "\", line " (group (1+ digit))) |
| 1314 | 1 2) | 1590 | 1 2) |
| 1315 | (,(rx " in file " (group (1+ not-newline)) " on line " | 1591 | (,(rx " in file " (group (1+ not-newline)) " on line " |
| 1316 | (group (1+ digit))) | 1592 | (group (1+ digit))) |
| 1317 | 1 2) | 1593 | 1 2) |
| 1318 | ;; pdb stack trace | ||
| 1319 | (,(rx line-start "> " (group (1+ (not (any "(\"<")))) | 1594 | (,(rx line-start "> " (group (1+ (not (any "(\"<")))) |
| 1320 | "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()") | 1595 | "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()") |
| 1321 | 1 2)) | 1596 | 1 2)) |
| 1322 | "`compilation-error-regexp-alist' for inferior Python.") | 1597 | "`compilation-error-regexp-alist' for inferior Python." |
| 1598 | :type '(alist string) | ||
| 1599 | :group 'python) | ||
| 1600 | |||
| 1601 | (defun python-shell-get-process-name (dedicated) | ||
| 1602 | "Calculate the appropriate process name for inferior Python process. | ||
| 1603 | If DEDICATED is t and the variable `buffer-file-name' is non-nil | ||
| 1604 | returns a string with the form | ||
| 1605 | `python-shell-buffer-name'[variable `buffer-file-name'] else | ||
| 1606 | returns the value of `python-shell-buffer-name'." | ||
| 1607 | (let ((process-name | ||
| 1608 | (if (and dedicated | ||
| 1609 | buffer-file-name) | ||
| 1610 | (format "%s[%s]" python-shell-buffer-name buffer-file-name) | ||
| 1611 | (format "%s" python-shell-buffer-name)))) | ||
| 1612 | process-name)) | ||
| 1613 | |||
| 1614 | (defun python-shell-internal-get-process-name () | ||
| 1615 | "Calculate the appropriate process name for Internal Python process. | ||
| 1616 | The name is calculated from `python-shell-global-buffer-name' and | ||
| 1617 | a hash of all relevant global shell settings in order to ensure | ||
| 1618 | uniqueness for different types of configurations." | ||
| 1619 | (format "%s [%s]" | ||
| 1620 | python-shell-internal-buffer-name | ||
| 1621 | (md5 | ||
| 1622 | (concat | ||
| 1623 | (python-shell-parse-command) | ||
| 1624 | python-shell-prompt-regexp | ||
| 1625 | python-shell-prompt-block-regexp | ||
| 1626 | python-shell-prompt-output-regexp | ||
| 1627 | (mapconcat #'symbol-value python-shell-setup-codes "") | ||
| 1628 | (mapconcat #'identity python-shell-process-environment "") | ||
| 1629 | (mapconcat #'identity python-shell-extra-pythonpaths "") | ||
| 1630 | (mapconcat #'identity python-shell-exec-path "") | ||
| 1631 | (or python-shell-virtualenv-path "") | ||
| 1632 | (mapconcat #'identity python-shell-exec-path ""))))) | ||
| 1633 | |||
| 1634 | (defun python-shell-parse-command () | ||
| 1635 | "Calculate the string used to execute the inferior Python process." | ||
| 1636 | (format "%s %s" python-shell-interpreter python-shell-interpreter-args)) | ||
| 1637 | |||
| 1638 | (defun python-shell-calculate-process-environment () | ||
| 1639 | "Calculate process environment given `python-shell-virtualenv-path'." | ||
| 1640 | (let ((process-environment (append | ||
| 1641 | python-shell-process-environment | ||
| 1642 | process-environment nil)) | ||
| 1643 | (virtualenv (if python-shell-virtualenv-path | ||
| 1644 | (directory-file-name python-shell-virtualenv-path) | ||
| 1645 | nil))) | ||
| 1646 | (when python-shell-extra-pythonpaths | ||
| 1647 | (setenv "PYTHONPATH" | ||
| 1648 | (format "%s%s%s" | ||
| 1649 | (mapconcat 'identity | ||
| 1650 | python-shell-extra-pythonpaths | ||
| 1651 | path-separator) | ||
| 1652 | path-separator | ||
| 1653 | (or (getenv "PYTHONPATH") "")))) | ||
| 1654 | (if (not virtualenv) | ||
| 1655 | process-environment | ||
| 1656 | (setenv "PYTHONHOME" nil) | ||
| 1657 | (setenv "PATH" (format "%s/bin%s%s" | ||
| 1658 | virtualenv path-separator | ||
| 1659 | (or (getenv "PATH") ""))) | ||
| 1660 | (setenv "VIRTUAL_ENV" virtualenv)) | ||
| 1661 | process-environment)) | ||
| 1662 | |||
| 1663 | (defun python-shell-calculate-exec-path () | ||
| 1664 | "Calculate exec path given `python-shell-virtualenv-path'." | ||
| 1665 | (let ((path (append python-shell-exec-path | ||
| 1666 | exec-path nil))) | ||
| 1667 | (if (not python-shell-virtualenv-path) | ||
| 1668 | path | ||
| 1669 | (cons (format "%s/bin" | ||
| 1670 | (directory-file-name python-shell-virtualenv-path)) | ||
| 1671 | path)))) | ||
| 1672 | |||
| 1673 | (defun python-comint-output-filter-function (output) | ||
| 1674 | "Hook run after content is put into comint buffer. | ||
| 1675 | OUTPUT is a string with the contents of the buffer." | ||
| 1676 | (ansi-color-filter-apply output)) | ||
| 1677 | |||
| 1678 | (defvar python-shell--parent-buffer nil) | ||
| 1679 | |||
| 1680 | (defvar python-shell-output-syntax-table | ||
| 1681 | (let ((table (make-syntax-table python-dotty-syntax-table))) | ||
| 1682 | (modify-syntax-entry ?\' "." table) | ||
| 1683 | (modify-syntax-entry ?\" "." table) | ||
| 1684 | (modify-syntax-entry ?\( "." table) | ||
| 1685 | (modify-syntax-entry ?\[ "." table) | ||
| 1686 | (modify-syntax-entry ?\{ "." table) | ||
| 1687 | (modify-syntax-entry ?\) "." table) | ||
| 1688 | (modify-syntax-entry ?\] "." table) | ||
| 1689 | (modify-syntax-entry ?\} "." table) | ||
| 1690 | table) | ||
| 1691 | "Syntax table for shell output. | ||
| 1692 | It makes parens and quotes be treated as punctuation chars.") | ||
| 1323 | 1693 | ||
| 1324 | (defvar inferior-python-mode-map | ||
| 1325 | (let ((map (make-sparse-keymap))) | ||
| 1326 | ;; This will inherit from comint-mode-map. | ||
| 1327 | (define-key map "\C-c\C-l" 'python-load-file) | ||
| 1328 | (define-key map "\C-c\C-v" 'python-check) | ||
| 1329 | ;; Note that we _can_ still use these commands which send to the | ||
| 1330 | ;; Python process even at the prompt if we have a normal prompt, | ||
| 1331 | ;; i.e. '>>> ' and not '... '. See the comment before | ||
| 1332 | ;; python-send-region. Fixme: uncomment these if we address that. | ||
| 1333 | |||
| 1334 | ;; (define-key map [(meta ?\t)] 'python-complete-symbol) | ||
| 1335 | ;; (define-key map "\C-c\C-f" 'python-describe-symbol) | ||
| 1336 | map)) | ||
| 1337 | |||
| 1338 | (defvar inferior-python-mode-syntax-table | ||
| 1339 | (let ((st (make-syntax-table python-mode-syntax-table))) | ||
| 1340 | ;; Don't get confused by apostrophes in the process's output (e.g. if | ||
| 1341 | ;; you execute "help(os)"). | ||
| 1342 | (modify-syntax-entry ?\' "." st) | ||
| 1343 | ;; Maybe we should do the same for double quotes? | ||
| 1344 | ;; (modify-syntax-entry ?\" "." st) | ||
| 1345 | st)) | ||
| 1346 | |||
| 1347 | ;; Autoloaded. | ||
| 1348 | (declare-function compilation-shell-minor-mode "compile" (&optional arg)) | ||
| 1349 | |||
| 1350 | (defvar python--prompt-regexp nil) | ||
| 1351 | |||
| 1352 | (defun python--set-prompt-regexp () | ||
| 1353 | (let ((prompt (cdr-safe (or (assoc python-python-command | ||
| 1354 | python-shell-prompt-alist) | ||
| 1355 | (assq t python-shell-prompt-alist)))) | ||
| 1356 | (cprompt (cdr-safe (or (assoc python-python-command | ||
| 1357 | python-shell-continuation-prompt-alist) | ||
| 1358 | (assq t python-shell-continuation-prompt-alist))))) | ||
| 1359 | (set (make-local-variable 'comint-prompt-regexp) | ||
| 1360 | (concat "\\(" | ||
| 1361 | (mapconcat 'identity | ||
| 1362 | (delq nil (list prompt cprompt "^([Pp]db) ")) | ||
| 1363 | "\\|") | ||
| 1364 | "\\)")) | ||
| 1365 | (set (make-local-variable 'python--prompt-regexp) prompt))) | ||
| 1366 | |||
| 1367 | ;; Fixme: This should inherit some stuff from `python-mode', but I'm | ||
| 1368 | ;; not sure how much: at least some keybindings, like C-c C-f; | ||
| 1369 | ;; syntax?; font-locking, e.g. for triple-quoted strings? | ||
| 1370 | (define-derived-mode inferior-python-mode comint-mode "Inferior Python" | 1694 | (define-derived-mode inferior-python-mode comint-mode "Inferior Python" |
| 1371 | "Major mode for interacting with an inferior Python process. | 1695 | "Major mode for Python inferior process. |
| 1372 | A Python process can be started with \\[run-python]. | 1696 | Runs a Python interpreter as a subprocess of Emacs, with Python |
| 1373 | 1697 | I/O through an Emacs buffer. Variables | |
| 1374 | Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in | 1698 | `python-shell-interpreter' and `python-shell-interpreter-args' |
| 1375 | that order. | 1699 | controls which Python interpreter is run. Variables |
| 1376 | 1700 | `python-shell-prompt-regexp', | |
| 1377 | You can send text to the inferior Python process from other buffers | 1701 | `python-shell-prompt-output-regexp', |
| 1378 | containing Python source. | 1702 | `python-shell-prompt-block-regexp', |
| 1379 | * \\[python-switch-to-python] switches the current buffer to the Python | 1703 | `python-shell-enable-font-lock', |
| 1380 | process buffer. | 1704 | `python-shell-completion-setup-code', |
| 1381 | * \\[python-send-region] sends the current region to the Python process. | 1705 | `python-shell-completion-string-code', |
| 1382 | * \\[python-send-region-and-go] switches to the Python process buffer | 1706 | `python-shell-completion-module-string-code', |
| 1383 | after sending the text. | 1707 | `python-eldoc-setup-code', `python-eldoc-string-code', |
| 1384 | For running multiple processes in multiple buffers, see `run-python' and | 1708 | `python-ffap-setup-code' and `python-ffap-string-code' can |
| 1385 | `python-buffer'. | 1709 | customize this mode for different Python interpreters. |
| 1386 | 1710 | ||
| 1387 | \\{inferior-python-mode-map}" | 1711 | You can also add additional setup code to be run at |
| 1388 | :group 'python | 1712 | initialization of the interpreter via `python-shell-setup-codes' |
| 1389 | (require 'ansi-color) ; for ipython | 1713 | variable. |
| 1714 | |||
| 1715 | \(Type \\[describe-mode] in the process buffer for a list of commands.)" | ||
| 1716 | (and python-shell--parent-buffer | ||
| 1717 | (python-util-clone-local-variables python-shell--parent-buffer)) | ||
| 1718 | (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)" | ||
| 1719 | python-shell-prompt-regexp | ||
| 1720 | python-shell-prompt-block-regexp | ||
| 1721 | python-shell-prompt-pdb-regexp)) | ||
| 1390 | (setq mode-line-process '(":%s")) | 1722 | (setq mode-line-process '(":%s")) |
| 1391 | (set (make-local-variable 'comint-input-filter) 'python-input-filter) | 1723 | (make-local-variable 'comint-output-filter-functions) |
| 1392 | (add-hook 'comint-preoutput-filter-functions #'python-preoutput-filter | 1724 | (add-hook 'comint-output-filter-functions |
| 1393 | nil t) | 1725 | 'python-comint-output-filter-function) |
| 1394 | (python--set-prompt-regexp) | 1726 | (add-hook 'comint-output-filter-functions |
| 1727 | 'python-pdbtrack-comint-output-filter-function) | ||
| 1395 | (set (make-local-variable 'compilation-error-regexp-alist) | 1728 | (set (make-local-variable 'compilation-error-regexp-alist) |
| 1396 | python-compilation-regexp-alist) | 1729 | python-shell-compilation-regexp-alist) |
| 1730 | (define-key inferior-python-mode-map [remap complete-symbol] | ||
| 1731 | 'completion-at-point) | ||
| 1732 | (add-hook 'completion-at-point-functions | ||
| 1733 | 'python-shell-completion-complete-at-point nil 'local) | ||
| 1734 | (add-to-list (make-local-variable 'comint-dynamic-complete-functions) | ||
| 1735 | 'python-shell-completion-complete-at-point) | ||
| 1736 | (define-key inferior-python-mode-map "\t" | ||
| 1737 | 'python-shell-completion-complete-or-indent) | ||
| 1738 | (make-local-variable 'python-pdbtrack-buffers-to-kill) | ||
| 1739 | (make-local-variable 'python-pdbtrack-tracked-buffer) | ||
| 1740 | (make-local-variable 'python-shell-internal-last-output) | ||
| 1741 | (when python-shell-enable-font-lock | ||
| 1742 | (set-syntax-table python-mode-syntax-table) | ||
| 1743 | (set (make-local-variable 'font-lock-defaults) | ||
| 1744 | '(python-font-lock-keywords nil nil nil nil)) | ||
| 1745 | (set (make-local-variable 'syntax-propertize-function) | ||
| 1746 | (eval | ||
| 1747 | ;; XXX: Unfortunately eval is needed here to make use of the | ||
| 1748 | ;; dynamic value of `comint-prompt-regexp'. | ||
| 1749 | `(syntax-propertize-rules | ||
| 1750 | (,comint-prompt-regexp | ||
| 1751 | (0 (ignore | ||
| 1752 | (put-text-property | ||
| 1753 | comint-last-input-start end 'syntax-table | ||
| 1754 | python-shell-output-syntax-table) | ||
| 1755 | ;; XXX: This might look weird, but it is the easiest | ||
| 1756 | ;; way to ensure font lock gets cleaned up before the | ||
| 1757 | ;; current prompt, which is needed for unclosed | ||
| 1758 | ;; strings to not mess up with current input. | ||
| 1759 | (font-lock-unfontify-region comint-last-input-start end)))) | ||
| 1760 | (,(python-rx string-delimiter) | ||
| 1761 | (0 (ignore | ||
| 1762 | (and (not (eq (get-text-property start 'field) 'output)) | ||
| 1763 | (python-syntax-stringify))))))))) | ||
| 1397 | (compilation-shell-minor-mode 1)) | 1764 | (compilation-shell-minor-mode 1)) |
| 1398 | 1765 | ||
| 1399 | (defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'" | 1766 | (defun python-shell-make-comint (cmd proc-name &optional pop internal) |
| 1400 | "Input matching this regexp is not saved on the history list. | 1767 | "Create a python shell comint buffer. |
| 1401 | Default ignores all inputs of 0, 1, or 2 non-blank characters." | 1768 | CMD is the python command to be executed and PROC-NAME is the |
| 1402 | :type 'regexp | 1769 | process name the comint buffer will get. After the comint buffer |
| 1403 | :group 'python) | 1770 | is created the `inferior-python-mode' is activated. When |
| 1404 | 1771 | optional argument POP is non-nil the buffer is shown. When | |
| 1405 | (defcustom python-remove-cwd-from-path t | 1772 | optional argument INTERNAL is non-nil this process is run on a |
| 1406 | "Whether to allow loading of Python modules from the current directory. | 1773 | buffer with a name that starts with a space, following the Emacs |
| 1407 | If this is non-nil, Emacs removes '' from sys.path when starting | 1774 | convention for temporary/internal buffers, and also makes sure |
| 1408 | an inferior Python process. This is the default, for security | 1775 | the user is not queried for confirmation when the process is |
| 1409 | reasons, as it is easy for the Python process to be started | 1776 | killed." |
| 1410 | without the user's realization (e.g. to perform completion)." | 1777 | (save-excursion |
| 1411 | :type 'boolean | 1778 | (let* ((proc-buffer-name |
| 1412 | :group 'python | 1779 | (format (if (not internal) "*%s*" " *%s*") proc-name)) |
| 1413 | :version "23.3") | 1780 | (process-environment (python-shell-calculate-process-environment)) |
| 1414 | 1781 | (exec-path (python-shell-calculate-exec-path))) | |
| 1415 | (defun python-input-filter (str) | 1782 | (when (not (comint-check-proc proc-buffer-name)) |
| 1416 | "`comint-input-filter' function for inferior Python. | 1783 | (let* ((cmdlist (split-string-and-unquote cmd)) |
| 1417 | Don't save anything for STR matching `inferior-python-filter-regexp'." | 1784 | (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name |
| 1418 | (not (string-match inferior-python-filter-regexp str))) | 1785 | (car cmdlist) nil (cdr cmdlist))) |
| 1419 | 1786 | (python-shell--parent-buffer (current-buffer)) | |
| 1420 | ;; Fixme: Loses with quoted whitespace. | 1787 | (process (get-buffer-process buffer))) |
| 1421 | (defun python-args-to-list (string) | 1788 | (with-current-buffer buffer |
| 1422 | (let ((where (string-match "[ \t]" string))) | 1789 | (inferior-python-mode)) |
| 1423 | (cond ((null where) (list string)) | 1790 | (accept-process-output process) |
| 1424 | ((not (= where 0)) | 1791 | (and pop (pop-to-buffer buffer t)) |
| 1425 | (cons (substring string 0 where) | 1792 | (and internal (set-process-query-on-exit-flag process nil)))) |
| 1426 | (python-args-to-list (substring string (+ 1 where))))) | 1793 | proc-buffer-name))) |
| 1427 | (t (let ((pos (string-match "[^ \t]" string))) | ||
| 1428 | (if pos (python-args-to-list (substring string pos)))))))) | ||
| 1429 | |||
| 1430 | (defvar python-preoutput-result nil | ||
| 1431 | "Data from last `_emacs_out' line seen by the preoutput filter.") | ||
| 1432 | |||
| 1433 | (defvar python-preoutput-continuation nil | ||
| 1434 | "If non-nil, funcall this when `python-preoutput-filter' sees `_emacs_ok'.") | ||
| 1435 | |||
| 1436 | (defvar python-preoutput-leftover nil) | ||
| 1437 | (defvar python-preoutput-skip-next-prompt nil) | ||
| 1438 | |||
| 1439 | ;; Using this stops us getting lines in the buffer like | ||
| 1440 | ;; >>> ... ... >>> | ||
| 1441 | ;; Also look for (and delete) an `_emacs_ok' string and call | ||
| 1442 | ;; `python-preoutput-continuation' if we get it. | ||
| 1443 | (defun python-preoutput-filter (s) | ||
| 1444 | "`comint-preoutput-filter-functions' function: ignore prompts not at bol." | ||
| 1445 | (when python-preoutput-leftover | ||
| 1446 | (setq s (concat python-preoutput-leftover s)) | ||
| 1447 | (setq python-preoutput-leftover nil)) | ||
| 1448 | (let ((start 0) | ||
| 1449 | (res "")) | ||
| 1450 | ;; First process whole lines. | ||
| 1451 | (while (string-match "\n" s start) | ||
| 1452 | (let ((line (substring s start (setq start (match-end 0))))) | ||
| 1453 | ;; Skip prompt if needed. | ||
| 1454 | (when (and python-preoutput-skip-next-prompt | ||
| 1455 | (string-match comint-prompt-regexp line)) | ||
| 1456 | (setq python-preoutput-skip-next-prompt nil) | ||
| 1457 | (setq line (substring line (match-end 0)))) | ||
| 1458 | ;; Recognize special _emacs_out lines. | ||
| 1459 | (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line) | ||
| 1460 | (local-variable-p 'python-preoutput-result)) | ||
| 1461 | (progn | ||
| 1462 | (setq python-preoutput-result (match-string 1 line)) | ||
| 1463 | (set (make-local-variable 'python-preoutput-skip-next-prompt) t)) | ||
| 1464 | (setq res (concat res line))))) | ||
| 1465 | ;; Then process the remaining partial line. | ||
| 1466 | (unless (zerop start) (setq s (substring s start))) | ||
| 1467 | (cond ((and (string-match comint-prompt-regexp s) | ||
| 1468 | ;; Drop this prompt if it follows an _emacs_out... | ||
| 1469 | (or python-preoutput-skip-next-prompt | ||
| 1470 | ;; ... or if it's not gonna be inserted at BOL. | ||
| 1471 | ;; Maybe we could be more selective here. | ||
| 1472 | (if (zerop (length res)) | ||
| 1473 | (not (bolp)) | ||
| 1474 | (string-match ".\\'" res)))) | ||
| 1475 | ;; The need for this seems to be system-dependent: | ||
| 1476 | ;; What is this all about, exactly? --Stef | ||
| 1477 | ;; (if (and (eq ?. (aref s 0))) | ||
| 1478 | ;; (accept-process-output (get-buffer-process (current-buffer)) 1)) | ||
| 1479 | (setq python-preoutput-skip-next-prompt nil) | ||
| 1480 | res) | ||
| 1481 | ((let ((end (min (length "_emacs_out ") (length s)))) | ||
| 1482 | (eq t (compare-strings s nil end "_emacs_out " nil end))) | ||
| 1483 | ;; The leftover string is a prefix of _emacs_out so we don't know | ||
| 1484 | ;; yet whether it's an _emacs_out or something else: wait until we | ||
| 1485 | ;; get more output so we can resolve this ambiguity. | ||
| 1486 | (set (make-local-variable 'python-preoutput-leftover) s) | ||
| 1487 | res) | ||
| 1488 | (t (concat res s))))) | ||
| 1489 | |||
| 1490 | (autoload 'comint-check-proc "comint") | ||
| 1491 | |||
| 1492 | (defvar python-version-checked nil) | ||
| 1493 | (defun python-check-version (cmd) | ||
| 1494 | "Check that CMD runs a suitable version of Python." | ||
| 1495 | ;; Fixme: Check on Jython. | ||
| 1496 | (unless (or python-version-checked | ||
| 1497 | (equal 0 (string-match (regexp-quote python-python-command) | ||
| 1498 | cmd))) | ||
| 1499 | (unless (shell-command-to-string cmd) | ||
| 1500 | (error "Can't run Python command `%s'" cmd)) | ||
| 1501 | (let* ((res (shell-command-to-string | ||
| 1502 | (concat cmd | ||
| 1503 | " -c \"from sys import version_info;\ | ||
| 1504 | print version_info >= (2, 2) and version_info < (3, 0)\"")))) | ||
| 1505 | (unless (string-match "True" res) | ||
| 1506 | (error "Only Python versions >= 2.2 and < 3.0 are supported"))) | ||
| 1507 | (setq python-version-checked t))) | ||
| 1508 | 1794 | ||
| 1509 | ;;;###autoload | 1795 | ;;;###autoload |
| 1510 | (defun run-python (&optional cmd noshow new) | 1796 | (defun run-python (cmd &optional dedicated show) |
| 1511 | "Run an inferior Python process, input and output via buffer *Python*. | 1797 | "Run an inferior Python process. |
| 1512 | CMD is the Python command to run. NOSHOW non-nil means don't | 1798 | Input and output via buffer named after |
| 1513 | show the buffer automatically. | 1799 | `python-shell-buffer-name'. If there is a process already |
| 1514 | 1800 | running in that buffer, just switch to it. | |
| 1515 | Interactively, a prefix arg means to prompt for the initial | 1801 | |
| 1516 | Python command line (default is `python-command'). | 1802 | With argument, allows you to define CMD so you can edit the |
| 1517 | 1803 | command used to call the interpreter and define DEDICATED, so a | |
| 1518 | A new process is started if one isn't running attached to | 1804 | dedicated process for the current buffer is open. When numeric |
| 1519 | `python-buffer', or if called from Lisp with non-nil arg NEW. | 1805 | prefix arg is other than 0 or 4 do not SHOW. |
| 1520 | Otherwise, if a process is already running in `python-buffer', | 1806 | |
| 1521 | switch to that buffer. | 1807 | Runs the hook `inferior-python-mode-hook' (after the |
| 1522 | 1808 | `comint-mode-hook' is run). \(Type \\[describe-mode] in the | |
| 1523 | This command runs the hook `inferior-python-mode-hook' after | 1809 | process buffer for a list of commands.)" |
| 1524 | running `comint-mode-hook'. Type \\[describe-mode] in the | 1810 | (interactive |
| 1525 | process buffer for a list of commands. | 1811 | (if current-prefix-arg |
| 1526 | 1812 | (list | |
| 1527 | By default, Emacs inhibits the loading of Python modules from the | 1813 | (read-string "Run Python: " (python-shell-parse-command)) |
| 1528 | current working directory, for security reasons. To disable this | 1814 | (y-or-n-p "Make dedicated process? ") |
| 1529 | behavior, change `python-remove-cwd-from-path' to nil." | 1815 | (= (prefix-numeric-value current-prefix-arg) 4)) |
| 1530 | (interactive (if current-prefix-arg | 1816 | (list (python-shell-parse-command) nil t))) |
| 1531 | (list (read-string "Run Python: " python-command) nil t) | 1817 | (python-shell-make-comint |
| 1532 | (list python-command))) | 1818 | cmd (python-shell-get-process-name dedicated) show) |
| 1533 | (require 'ansi-color) ; for ipython | 1819 | dedicated) |
| 1534 | (unless cmd (setq cmd python-command)) | 1820 | |
| 1535 | (python-check-version cmd) | 1821 | (defun run-python-internal () |
| 1536 | (setq python-command cmd) | 1822 | "Run an inferior Internal Python process. |
| 1537 | ;; Fixme: Consider making `python-buffer' buffer-local as a buffer | 1823 | Input and output via buffer named after |
| 1538 | ;; (not a name) in Python buffers from which `run-python' &c is | 1824 | `python-shell-internal-buffer-name' and what |
| 1539 | ;; invoked. Would support multiple processes better. | 1825 | `python-shell-internal-get-process-name' returns. |
| 1540 | (when (or new (not (comint-check-proc python-buffer))) | 1826 | |
| 1541 | (with-current-buffer | 1827 | This new kind of shell is intended to be used for generic |
| 1542 | (let* ((cmdlist | 1828 | communication related to defined configurations, the main |
| 1543 | (append (python-args-to-list cmd) '("-i") | 1829 | difference with global or dedicated shells is that these ones are |
| 1544 | (if python-remove-cwd-from-path | 1830 | attached to a configuration, not a buffer. This means that can |
| 1545 | '("-c" "import sys; sys.path.remove('')")))) | 1831 | be used for example to retrieve the sys.path and other stuff, |
| 1546 | (path (getenv "PYTHONPATH")) | 1832 | without messing with user shells. Note that |
| 1547 | (process-environment ; to import emacs.py | 1833 | `python-shell-enable-font-lock' and `inferior-python-mode-hook' |
| 1548 | (cons (concat "PYTHONPATH=" | 1834 | are set to nil for these shells, so setup codes are not sent at |
| 1549 | (if path (concat path path-separator)) | 1835 | startup." |
| 1550 | data-directory) | 1836 | (let ((python-shell-enable-font-lock nil) |
| 1551 | process-environment)) | 1837 | (inferior-python-mode-hook nil)) |
| 1552 | ;; If we use a pipe, Unicode characters are not printed | 1838 | (get-buffer-process |
| 1553 | ;; correctly (Bug#5794) and IPython does not work at | 1839 | (python-shell-make-comint |
| 1554 | ;; all (Bug#5390). | 1840 | (python-shell-parse-command) |
| 1555 | (process-connection-type t)) | 1841 | (python-shell-internal-get-process-name) nil t)))) |
| 1556 | (apply 'make-comint-in-buffer "Python" | 1842 | |
| 1557 | (generate-new-buffer "*Python*") | 1843 | (defun python-shell-get-process () |
| 1558 | (car cmdlist) nil (cdr cmdlist))) | 1844 | "Get inferior Python process for current buffer and return it." |
| 1559 | (setq-default python-buffer (current-buffer)) | 1845 | (let* ((dedicated-proc-name (python-shell-get-process-name t)) |
| 1560 | (setq python-buffer (current-buffer)) | 1846 | (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name)) |
| 1561 | (accept-process-output (get-buffer-process python-buffer) 5) | 1847 | (global-proc-name (python-shell-get-process-name nil)) |
| 1562 | (inferior-python-mode) | 1848 | (global-proc-buffer-name (format "*%s*" global-proc-name)) |
| 1563 | ;; Load function definitions we need. | 1849 | (dedicated-running (comint-check-proc dedicated-proc-buffer-name)) |
| 1564 | ;; Before the preoutput function was used, this was done via -c in | 1850 | (global-running (comint-check-proc global-proc-buffer-name))) |
| 1565 | ;; cmdlist, but that loses the banner and doesn't run the startup | 1851 | ;; Always prefer dedicated |
| 1566 | ;; file. The code might be inline here, but there's enough that it | 1852 | (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name) |
| 1567 | ;; seems worth putting in a separate file, and it's probably cleaner | 1853 | (and global-running global-proc-buffer-name))))) |
| 1568 | ;; to put it in a module. | 1854 | |
| 1569 | ;; Ensure we're at a prompt before doing anything else. | 1855 | (defun python-shell-get-or-create-process () |
| 1570 | (python-send-string "import emacs") | 1856 | "Get or create an inferior Python process for current buffer and return it." |
| 1571 | ;; The following line was meant to ensure that we're at a prompt | 1857 | (let* ((dedicated-proc-name (python-shell-get-process-name t)) |
| 1572 | ;; before doing anything else. However, this can cause Emacs to | 1858 | (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name)) |
| 1573 | ;; hang waiting for a response, if that Python function fails | 1859 | (global-proc-name (python-shell-get-process-name nil)) |
| 1574 | ;; (i.e. raises an exception). | 1860 | (global-proc-buffer-name (format "*%s*" global-proc-name)) |
| 1575 | ;; (python-send-receive "print '_emacs_out ()'") | 1861 | (dedicated-running (comint-check-proc dedicated-proc-buffer-name)) |
| 1576 | )) | 1862 | (global-running (comint-check-proc global-proc-buffer-name)) |
| 1577 | (if (derived-mode-p 'python-mode) | 1863 | (current-prefix-arg 16)) |
| 1578 | (setq python-buffer (default-value 'python-buffer))) ; buffer-local | 1864 | (when (and (not dedicated-running) (not global-running)) |
| 1579 | ;; Without this, help output goes into the inferior python buffer if | 1865 | (if (call-interactively 'run-python) |
| 1580 | ;; the process isn't already running. | 1866 | (setq dedicated-running t) |
| 1581 | (sit-for 1 t) ;Should we use accept-process-output instead? --Stef | 1867 | (setq global-running t))) |
| 1582 | (unless noshow (pop-to-buffer python-buffer t))) | 1868 | ;; Always prefer dedicated |
| 1583 | 1869 | (get-buffer-process (if dedicated-running | |
| 1584 | (defun python-send-command (command) | 1870 | dedicated-proc-buffer-name |
| 1585 | "Like `python-send-string' but resets `compilation-shell-minor-mode'." | 1871 | global-proc-buffer-name)))) |
| 1586 | (when (python-check-comint-prompt) | 1872 | |
| 1587 | (with-current-buffer (process-buffer (python-proc)) | 1873 | (defvar python-shell-internal-buffer nil |
| 1588 | (goto-char (point-max)) | 1874 | "Current internal shell buffer for the current buffer. |
| 1589 | (compilation-forget-errors) | 1875 | This is really not necessary at all for the code to work but it's |
| 1590 | (python-send-string command) | 1876 | there for compatibility with CEDET.") |
| 1591 | (setq compilation-last-buffer (current-buffer))))) | 1877 | |
| 1592 | 1878 | (defvar python-shell-internal-last-output nil | |
| 1593 | (defun python-send-region (start end) | 1879 | "Last output captured by the internal shell. |
| 1594 | "Send the region to the inferior Python process." | 1880 | This is really not necessary at all for the code to work but it's |
| 1595 | ;; The region is evaluated from a temporary file. This avoids | 1881 | there for compatibility with CEDET.") |
| 1596 | ;; problems with blank lines, which have different semantics | 1882 | |
| 1597 | ;; interactively and in files. It also saves the inferior process | 1883 | (defun python-shell-internal-get-or-create-process () |
| 1598 | ;; buffer filling up with interpreter prompts. We need a Python | 1884 | "Get or create an inferior Internal Python process." |
| 1599 | ;; function to remove the temporary file when it has been evaluated | 1885 | (let* ((proc-name (python-shell-internal-get-process-name)) |
| 1600 | ;; (though we could probably do it in Lisp with a Comint output | 1886 | (proc-buffer-name (format " *%s*" proc-name))) |
| 1601 | ;; filter). This function also catches exceptions and truncates | 1887 | (when (not (process-live-p proc-name)) |
| 1602 | ;; tracebacks not to mention the frame of the function itself. | 1888 | (run-python-internal) |
| 1603 | ;; | 1889 | (setq python-shell-internal-buffer proc-buffer-name) |
| 1604 | ;; The `compilation-shell-minor-mode' parsing takes care of relating | 1890 | ;; XXX: Why is this `sit-for' needed? |
| 1605 | ;; the reference to the temporary file to the source. | 1891 | ;; `python-shell-make-comint' calls `accept-process-output' |
| 1606 | ;; | 1892 | ;; already but it is not helping to get proper output on |
| 1607 | ;; Fixme: Write a `coding' header to the temp file if the region is | 1893 | ;; 'gnu/linux when the internal shell process is not running and |
| 1608 | ;; non-ASCII. | 1894 | ;; a call to `python-shell-internal-send-string' is issued. |
| 1609 | (interactive "r") | 1895 | (sit-for 0.1 t)) |
| 1610 | (let* ((f (make-temp-file "py")) | 1896 | (get-buffer-process proc-buffer-name))) |
| 1611 | (command | 1897 | |
| 1612 | ;; IPython puts the FakeModule module into __main__ so | 1898 | (define-obsolete-function-alias |
| 1613 | ;; emacs.eexecfile becomes useless. | 1899 | 'python-proc 'python-shell-internal-get-or-create-process "24.3") |
| 1614 | (if (string-match "^ipython" python-command) | 1900 | |
| 1615 | (format "execfile %S" f) | 1901 | (define-obsolete-variable-alias |
| 1616 | (format "emacs.eexecfile(%S)" f))) | 1902 | 'python-buffer 'python-shell-internal-buffer "24.3") |
| 1617 | (orig-start (copy-marker start))) | 1903 | |
| 1618 | (when (save-excursion | 1904 | (define-obsolete-variable-alias |
| 1619 | (goto-char start) | 1905 | 'python-preoutput-result 'python-shell-internal-last-output "24.3") |
| 1620 | (/= 0 (current-indentation))) ; need dummy block | 1906 | |
| 1621 | (save-excursion | 1907 | (defun python-shell-send-string (string &optional process msg) |
| 1622 | (goto-char orig-start) | 1908 | "Send STRING to inferior Python PROCESS. |
| 1623 | ;; Wrong if we had indented code at buffer start. | 1909 | When MSG is non-nil messages the first line of STRING." |
| 1624 | (set-marker orig-start (line-beginning-position 0))) | ||
| 1625 | (write-region "if True:\n" nil f nil 'nomsg)) | ||
| 1626 | (write-region start end f t 'nomsg) | ||
| 1627 | (python-send-command command) | ||
| 1628 | (with-current-buffer (process-buffer (python-proc)) | ||
| 1629 | ;; Tell compile.el to redirect error locations in file `f' to | ||
| 1630 | ;; positions past marker `orig-start'. It has to be done *after* | ||
| 1631 | ;; `python-send-command''s call to `compilation-forget-errors'. | ||
| 1632 | (compilation-fake-loc orig-start f)))) | ||
| 1633 | |||
| 1634 | (defun python-send-string (string) | ||
| 1635 | "Evaluate STRING in inferior Python process." | ||
| 1636 | (interactive "sPython command: ") | 1910 | (interactive "sPython command: ") |
| 1637 | (comint-send-string (python-proc) string) | 1911 | (let ((process (or process (python-shell-get-or-create-process))) |
| 1638 | (unless (string-match "\n\\'" string) | 1912 | (lines (split-string string "\n" t))) |
| 1639 | ;; Make sure the text is properly LF-terminated. | 1913 | (and msg (message "Sent: %s..." (nth 0 lines))) |
| 1640 | (comint-send-string (python-proc) "\n")) | 1914 | (if (> (length lines) 1) |
| 1641 | (when (string-match "\n[ \t].*\n?\\'" string) | 1915 | (let* ((temporary-file-directory |
| 1642 | ;; If the string contains a final indented line, add a second newline so | 1916 | (if (file-remote-p default-directory) |
| 1643 | ;; as to make sure we terminate the multiline instruction. | 1917 | (concat (file-remote-p default-directory) "/tmp") |
| 1644 | (comint-send-string (python-proc) "\n"))) | 1918 | temporary-file-directory)) |
| 1645 | 1919 | (temp-file-name (make-temp-file "py")) | |
| 1646 | (defun python-send-buffer () | 1920 | (file-name (or (buffer-file-name) temp-file-name))) |
| 1647 | "Send the current buffer to the inferior Python process." | 1921 | (with-temp-file temp-file-name |
| 1648 | (interactive) | 1922 | (insert string) |
| 1649 | (python-send-region (point-min) (point-max))) | 1923 | (delete-trailing-whitespace)) |
| 1924 | (python-shell-send-file file-name process temp-file-name)) | ||
| 1925 | (comint-send-string process string) | ||
| 1926 | (when (or (not (string-match "\n$" string)) | ||
| 1927 | (string-match "\n[ \t].*\n?$" string)) | ||
| 1928 | (comint-send-string process "\n"))))) | ||
| 1929 | |||
| 1930 | (defvar python-shell-output-filter-in-progress nil) | ||
| 1931 | (defvar python-shell-output-filter-buffer nil) | ||
| 1932 | |||
| 1933 | (defun python-shell-output-filter (string) | ||
| 1934 | "Filter used in `python-shell-send-string-no-output' to grab output. | ||
| 1935 | STRING is the output received to this point from the process. | ||
| 1936 | This filter saves received output from the process in | ||
| 1937 | `python-shell-output-filter-buffer' and stops receiving it after | ||
| 1938 | detecting a prompt at the end of the buffer." | ||
| 1939 | (setq | ||
| 1940 | string (ansi-color-filter-apply string) | ||
| 1941 | python-shell-output-filter-buffer | ||
| 1942 | (concat python-shell-output-filter-buffer string)) | ||
| 1943 | (when (string-match | ||
| 1944 | ;; XXX: It seems on OSX an extra carriage return is attached | ||
| 1945 | ;; at the end of output, this handles that too. | ||
| 1946 | (format "\r?\n\\(?:%s\\|%s\\|%s\\)$" | ||
| 1947 | python-shell-prompt-regexp | ||
| 1948 | python-shell-prompt-block-regexp | ||
| 1949 | python-shell-prompt-pdb-regexp) | ||
| 1950 | python-shell-output-filter-buffer) | ||
| 1951 | ;; Output ends when `python-shell-output-filter-buffer' contains | ||
| 1952 | ;; the prompt attached at the end of it. | ||
| 1953 | (setq python-shell-output-filter-in-progress nil | ||
| 1954 | python-shell-output-filter-buffer | ||
| 1955 | (substring python-shell-output-filter-buffer | ||
| 1956 | 0 (match-beginning 0))) | ||
| 1957 | (when (and (> (length python-shell-prompt-output-regexp) 0) | ||
| 1958 | (string-match (concat "^" python-shell-prompt-output-regexp) | ||
| 1959 | python-shell-output-filter-buffer)) | ||
| 1960 | ;; Some shells, like iPython might append a prompt before the | ||
| 1961 | ;; output, clean that. | ||
| 1962 | (setq python-shell-output-filter-buffer | ||
| 1963 | (substring python-shell-output-filter-buffer (match-end 0))))) | ||
| 1964 | "") | ||
| 1965 | |||
| 1966 | (defun python-shell-send-string-no-output (string &optional process msg) | ||
| 1967 | "Send STRING to PROCESS and inhibit output. | ||
| 1968 | When MSG is non-nil messages the first line of STRING. Return | ||
| 1969 | the output." | ||
| 1970 | (let ((process (or process (python-shell-get-or-create-process))) | ||
| 1971 | (comint-preoutput-filter-functions | ||
| 1972 | '(python-shell-output-filter)) | ||
| 1973 | (python-shell-output-filter-in-progress t) | ||
| 1974 | (inhibit-quit t)) | ||
| 1975 | (or | ||
| 1976 | (with-local-quit | ||
| 1977 | (python-shell-send-string string process msg) | ||
| 1978 | (while python-shell-output-filter-in-progress | ||
| 1979 | ;; `python-shell-output-filter' takes care of setting | ||
| 1980 | ;; `python-shell-output-filter-in-progress' to NIL after it | ||
| 1981 | ;; detects end of output. | ||
| 1982 | (accept-process-output process)) | ||
| 1983 | (prog1 | ||
| 1984 | python-shell-output-filter-buffer | ||
| 1985 | (setq python-shell-output-filter-buffer nil))) | ||
| 1986 | (with-current-buffer (process-buffer process) | ||
| 1987 | (comint-interrupt-subjob))))) | ||
| 1988 | |||
| 1989 | (defun python-shell-internal-send-string (string) | ||
| 1990 | "Send STRING to the Internal Python interpreter. | ||
| 1991 | Returns the output. See `python-shell-send-string-no-output'." | ||
| 1992 | ;; XXX Remove `python-shell-internal-last-output' once CEDET is | ||
| 1993 | ;; updated to support this new mode. | ||
| 1994 | (setq python-shell-internal-last-output | ||
| 1995 | (python-shell-send-string-no-output | ||
| 1996 | ;; Makes this function compatible with the old | ||
| 1997 | ;; python-send-receive. (At least for CEDET). | ||
| 1998 | (replace-regexp-in-string "_emacs_out +" "" string) | ||
| 1999 | (python-shell-internal-get-or-create-process) nil))) | ||
| 2000 | |||
| 2001 | (define-obsolete-function-alias | ||
| 2002 | 'python-send-receive 'python-shell-internal-send-string "24.3") | ||
| 2003 | |||
| 2004 | (define-obsolete-function-alias | ||
| 2005 | 'python-send-string 'python-shell-internal-send-string "24.3") | ||
| 2006 | |||
| 2007 | (defun python-shell-send-region (start end) | ||
| 2008 | "Send the region delimited by START and END to inferior Python process." | ||
| 2009 | (interactive "r") | ||
| 2010 | (python-shell-send-string (buffer-substring start end) nil t)) | ||
| 1650 | 2011 | ||
| 1651 | ;; Fixme: Try to define the function or class within the relevant | 2012 | (defun python-shell-send-buffer (&optional arg) |
| 1652 | ;; module, not just at top level. | 2013 | "Send the entire buffer to inferior Python process. |
| 1653 | (defun python-send-defun () | 2014 | With prefix ARG allow execution of code inside blocks delimited |
| 1654 | "Send the current defun (class or method) to the inferior Python process." | 2015 | by \"if __name__== '__main__':\"" |
| 2016 | (interactive "P") | ||
| 2017 | (save-restriction | ||
| 2018 | (widen) | ||
| 2019 | (let ((str (buffer-substring (point-min) (point-max)))) | ||
| 2020 | (and | ||
| 2021 | (not arg) | ||
| 2022 | (setq str (replace-regexp-in-string | ||
| 2023 | (python-rx if-name-main) | ||
| 2024 | "if __name__ == '__main__ ':" str))) | ||
| 2025 | (python-shell-send-string str)))) | ||
| 2026 | |||
| 2027 | (defun python-shell-send-defun (arg) | ||
| 2028 | "Send the current defun to inferior Python process. | ||
| 2029 | When argument ARG is non-nil do not include decorators." | ||
| 2030 | (interactive "P") | ||
| 2031 | (save-excursion | ||
| 2032 | (python-shell-send-region | ||
| 2033 | (progn | ||
| 2034 | (end-of-line 1) | ||
| 2035 | (while (and (or (python-nav-beginning-of-defun) | ||
| 2036 | (beginning-of-line 1)) | ||
| 2037 | (> (current-indentation) 0))) | ||
| 2038 | (when (not arg) | ||
| 2039 | (while (and (forward-line -1) | ||
| 2040 | (looking-at (python-rx decorator)))) | ||
| 2041 | (forward-line 1)) | ||
| 2042 | (point-marker)) | ||
| 2043 | (progn | ||
| 2044 | (or (python-nav-end-of-defun) | ||
| 2045 | (end-of-line 1)) | ||
| 2046 | (point-marker))))) | ||
| 2047 | |||
| 2048 | (defun python-shell-send-file (file-name &optional process temp-file-name) | ||
| 2049 | "Send FILE-NAME to inferior Python PROCESS. | ||
| 2050 | If TEMP-FILE-NAME is passed then that file is used for processing | ||
| 2051 | instead, while internally the shell will continue to use | ||
| 2052 | FILE-NAME." | ||
| 2053 | (interactive "fFile to send: ") | ||
| 2054 | (let* ((process (or process (python-shell-get-or-create-process))) | ||
| 2055 | (temp-file-name (when temp-file-name | ||
| 2056 | (expand-file-name | ||
| 2057 | (or (file-remote-p temp-file-name 'localname) | ||
| 2058 | temp-file-name)))) | ||
| 2059 | (file-name (or (when file-name | ||
| 2060 | (expand-file-name | ||
| 2061 | (or (file-remote-p file-name 'localname) | ||
| 2062 | file-name))) | ||
| 2063 | temp-file-name))) | ||
| 2064 | (when (not file-name) | ||
| 2065 | (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil")) | ||
| 2066 | (python-shell-send-string | ||
| 2067 | (format | ||
| 2068 | (concat "__pyfile = open('''%s''');" | ||
| 2069 | "exec(compile(__pyfile.read(), '''%s''', 'exec'));" | ||
| 2070 | "__pyfile.close()") | ||
| 2071 | (or temp-file-name file-name) file-name) | ||
| 2072 | process))) | ||
| 2073 | |||
| 2074 | (defun python-shell-switch-to-shell () | ||
| 2075 | "Switch to inferior Python process buffer." | ||
| 1655 | (interactive) | 2076 | (interactive) |
| 1656 | (save-excursion (python-send-region (progn (beginning-of-defun) (point)) | 2077 | (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t)) |
| 1657 | (progn (end-of-defun) (point))))) | 2078 | |
| 2079 | (defun python-shell-send-setup-code () | ||
| 2080 | "Send all setup code for shell. | ||
| 2081 | This function takes the list of setup code to send from the | ||
| 2082 | `python-shell-setup-codes' list." | ||
| 2083 | (let ((process (get-buffer-process (current-buffer)))) | ||
| 2084 | (dolist (code python-shell-setup-codes) | ||
| 2085 | (when code | ||
| 2086 | (message "Sent %s" code) | ||
| 2087 | (python-shell-send-string | ||
| 2088 | (symbol-value code) process))))) | ||
| 2089 | |||
| 2090 | (add-hook 'inferior-python-mode-hook | ||
| 2091 | #'python-shell-send-setup-code) | ||
| 1658 | 2092 | ||
| 1659 | (defun python-switch-to-python (eob-p) | 2093 | |
| 1660 | "Switch to the Python process buffer, maybe starting new process. | 2094 | ;;; Shell completion |
| 1661 | With prefix arg, position cursor at end of buffer." | 2095 | |
| 1662 | (interactive "P") | 2096 | (defcustom python-shell-completion-setup-code |
| 1663 | (pop-to-buffer (process-buffer (python-proc)) t) ;Runs python if needed. | 2097 | "try: |
| 1664 | (when eob-p | 2098 | import readline |
| 1665 | (push-mark) | 2099 | except ImportError: |
| 1666 | (goto-char (point-max)))) | 2100 | def __COMPLETER_all_completions(text): [] |
| 1667 | 2101 | else: | |
| 1668 | (defun python-send-region-and-go (start end) | 2102 | import rlcompleter |
| 1669 | "Send the region to the inferior Python process. | 2103 | readline.set_completer(rlcompleter.Completer().complete) |
| 1670 | Then switch to the process buffer." | 2104 | def __COMPLETER_all_completions(text): |
| 1671 | (interactive "r") | 2105 | import sys |
| 1672 | (python-send-region start end) | 2106 | completions = [] |
| 1673 | (python-switch-to-python t)) | 2107 | try: |
| 1674 | 2108 | i = 0 | |
| 1675 | (defcustom python-source-modes '(python-mode jython-mode) | 2109 | while True: |
| 1676 | "Used to determine if a buffer contains Python source code. | 2110 | res = readline.get_completer()(text, i) |
| 1677 | If a file is loaded into a buffer that is in one of these major modes, | 2111 | if not res: break |
| 1678 | it is considered Python source by `python-load-file', which uses the | 2112 | i += 1 |
| 1679 | value to determine defaults." | 2113 | completions.append(res) |
| 1680 | :type '(repeat function) | 2114 | except NameError: |
| 2115 | pass | ||
| 2116 | return completions" | ||
| 2117 | "Code used to setup completion in inferior Python processes." | ||
| 2118 | :type 'string | ||
| 1681 | :group 'python) | 2119 | :group 'python) |
| 1682 | 2120 | ||
| 1683 | (defvar python-prev-dir/file nil | 2121 | (defcustom python-shell-completion-string-code |
| 1684 | "Caches (directory . file) pair used in the last `python-load-file' command. | 2122 | "';'.join(__COMPLETER_all_completions('''%s'''))\n" |
| 1685 | Used for determining the default in the next one.") | 2123 | "Python code used to get a string of completions separated by semicolons." |
| 1686 | 2124 | :type 'string | |
| 1687 | (autoload 'comint-get-source "comint") | 2125 | :group 'python) |
| 1688 | |||
| 1689 | (defun python-load-file (file-name) | ||
| 1690 | "Load a Python file FILE-NAME into the inferior Python process. | ||
| 1691 | If the file has extension `.py' import or reload it as a module. | ||
| 1692 | Treating it as a module keeps the global namespace clean, provides | ||
| 1693 | function location information for debugging, and supports users of | ||
| 1694 | module-qualified names." | ||
| 1695 | (interactive (comint-get-source "Load Python file: " python-prev-dir/file | ||
| 1696 | python-source-modes | ||
| 1697 | t)) ; because execfile needs exact name | ||
| 1698 | (comint-check-source file-name) ; Check to see if buffer needs saving. | ||
| 1699 | (setq python-prev-dir/file (cons (file-name-directory file-name) | ||
| 1700 | (file-name-nondirectory file-name))) | ||
| 1701 | (with-current-buffer (process-buffer (python-proc)) ;Runs python if needed. | ||
| 1702 | ;; Fixme: I'm not convinced by this logic from python-mode.el. | ||
| 1703 | (python-send-command | ||
| 1704 | (if (string-match "\\.py\\'" file-name) | ||
| 1705 | (let ((module (file-name-sans-extension | ||
| 1706 | (file-name-nondirectory file-name)))) | ||
| 1707 | (format "emacs.eimport(%S,%S)" | ||
| 1708 | module (file-name-directory file-name))) | ||
| 1709 | (format "execfile(%S)" file-name))) | ||
| 1710 | (message "%s loaded" file-name))) | ||
| 1711 | |||
| 1712 | (defun python-proc () | ||
| 1713 | "Return the current Python process. | ||
| 1714 | See variable `python-buffer'. Starts a new process if necessary." | ||
| 1715 | ;; Fixme: Maybe should look for another active process if there | ||
| 1716 | ;; isn't one for `python-buffer'. | ||
| 1717 | (unless (comint-check-proc python-buffer) | ||
| 1718 | (run-python nil t)) | ||
| 1719 | (get-buffer-process (if (derived-mode-p 'inferior-python-mode) | ||
| 1720 | (current-buffer) | ||
| 1721 | python-buffer))) | ||
| 1722 | |||
| 1723 | (defun python-set-proc () | ||
| 1724 | "Set the default value of `python-buffer' to correspond to this buffer. | ||
| 1725 | If the current buffer has a local value of `python-buffer', set the | ||
| 1726 | default (global) value to that. The associated Python process is | ||
| 1727 | the one that gets input from \\[python-send-region] et al when used | ||
| 1728 | in a buffer that doesn't have a local value of `python-buffer'." | ||
| 1729 | (interactive) | ||
| 1730 | (if (local-variable-p 'python-buffer) | ||
| 1731 | (setq-default python-buffer python-buffer) | ||
| 1732 | (error "No local value of `python-buffer'"))) | ||
| 1733 | |||
| 1734 | ;;;; Context-sensitive help. | ||
| 1735 | 2126 | ||
| 1736 | (defconst python-dotty-syntax-table | 2127 | (defcustom python-shell-completion-module-string-code "" |
| 1737 | (let ((table (make-syntax-table))) | 2128 | "Python code used to get completions separated by semicolons for imports. |
| 1738 | (set-char-table-parent table python-mode-syntax-table) | ||
| 1739 | (modify-syntax-entry ?. "_" table) | ||
| 1740 | table) | ||
| 1741 | "Syntax table giving `.' symbol syntax. | ||
| 1742 | Otherwise inherits from `python-mode-syntax-table'.") | ||
| 1743 | 2129 | ||
| 1744 | (defvar view-return-to-alist) | 2130 | For IPython v0.11, add the following line to |
| 1745 | (eval-when-compile (autoload 'help-buffer "help-fns")) | 2131 | `python-shell-completion-setup-code': |
| 1746 | 2132 | ||
| 1747 | (defvar python-imports) ; forward declaration | 2133 | from IPython.core.completerlib import module_completion |
| 1748 | 2134 | ||
| 1749 | ;; Fixme: Should this actually be used instead of info-look, i.e. be | 2135 | and use the following as the value of this variable: |
| 1750 | ;; bound to C-h S? [Probably not, since info-look may work in cases | ||
| 1751 | ;; where this doesn't.] | ||
| 1752 | (defun python-describe-symbol (symbol) | ||
| 1753 | "Get help on SYMBOL using `help'. | ||
| 1754 | Interactively, prompt for symbol. | ||
| 1755 | 2136 | ||
| 1756 | Symbol may be anything recognized by the interpreter's `help' | 2137 | ';'.join(module_completion('''%s'''))\n" |
| 1757 | command -- e.g. `CALLS' -- not just variables in scope in the | 2138 | :type 'string |
| 1758 | interpreter. This only works for Python version 2.2 or newer | 2139 | :group 'python) |
| 1759 | since earlier interpreters don't support `help'. | ||
| 1760 | 2140 | ||
| 1761 | In some cases where this doesn't find documentation, \\[info-lookup-symbol] | 2141 | (defcustom python-shell-completion-pdb-string-code |
| 1762 | will." | 2142 | "';'.join(globals().keys() + locals().keys())" |
| 1763 | ;; Note that we do this in the inferior process, not a separate one, to | 2143 | "Python code used to get completions separated by semicolons for [i]pdb." |
| 1764 | ;; ensure the environment is appropriate. | 2144 | :type 'string |
| 1765 | (interactive | 2145 | :group 'python) |
| 1766 | (let ((symbol (with-syntax-table python-dotty-syntax-table | 2146 | |
| 1767 | (current-word))) | 2147 | (defun python-shell-completion-get-completions (process line input) |
| 1768 | (enable-recursive-minibuffers t)) | 2148 | "Do completion at point for PROCESS. |
| 1769 | (list (read-string (if symbol | 2149 | LINE is used to detect the context on how to complete given |
| 1770 | (format "Describe symbol (default %s): " symbol) | 2150 | INPUT." |
| 1771 | "Describe symbol: ") | 2151 | (let* ((prompt |
| 1772 | nil nil symbol)))) | 2152 | ;; Get the last prompt for the inferior process |
| 1773 | (if (equal symbol "") (error "No symbol")) | 2153 | ;; buffer. This is used for the completion code selection |
| 1774 | ;; Ensure we have a suitable help buffer. | 2154 | ;; heuristic. |
| 1775 | ;; Fixme: Maybe process `Related help topics' a la help xrefs and | 2155 | (with-current-buffer (process-buffer process) |
| 1776 | ;; allow C-c C-f in help buffer. | 2156 | (buffer-substring-no-properties |
| 1777 | (let ((temp-buffer-show-hook ; avoid xref stuff | 2157 | (overlay-start comint-last-prompt-overlay) |
| 1778 | (lambda () | 2158 | (overlay-end comint-last-prompt-overlay)))) |
| 1779 | (toggle-read-only 1) | 2159 | (completion-context |
| 1780 | (setq view-return-to-alist | 2160 | ;; Check whether a prompt matches a pdb string, an import |
| 1781 | (list (cons (selected-window) help-return-method)))))) | 2161 | ;; statement or just the standard prompt and use the |
| 1782 | (with-output-to-temp-buffer (help-buffer) | 2162 | ;; correct python-shell-completion-*-code string |
| 1783 | (with-current-buffer standard-output | 2163 | (cond ((and (> (length python-shell-completion-pdb-string-code) 0) |
| 1784 | ;; Fixme: Is this actually useful? | 2164 | (string-match |
| 1785 | (help-setup-xref (list 'python-describe-symbol symbol) | 2165 | (concat "^" python-shell-prompt-pdb-regexp) prompt)) |
| 1786 | (called-interactively-p 'interactive)) | 2166 | 'pdb) |
| 1787 | (set (make-local-variable 'comint-redirect-subvert-readonly) t) | 2167 | ((and (> |
| 1788 | (help-print-return-message)))) | 2168 | (length python-shell-completion-module-string-code) 0) |
| 1789 | (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)" | 2169 | (string-match |
| 1790 | symbol python-imports) | 2170 | (concat "^" python-shell-prompt-regexp) prompt) |
| 1791 | "*Help*" (python-proc) nil nil)) | 2171 | (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line)) |
| 1792 | 2172 | 'import) | |
| 1793 | (add-to-list 'debug-ignored-errors "^No symbol") | 2173 | ((string-match |
| 1794 | 2174 | (concat "^" python-shell-prompt-regexp) prompt) | |
| 1795 | (defun python-send-receive (string) | 2175 | 'default) |
| 1796 | "Send STRING to inferior Python (if any) and return result. | 2176 | (t nil))) |
| 1797 | The result is what follows `_emacs_out' in the output. | 2177 | (completion-code |
| 1798 | This is a no-op if `python-check-comint-prompt' returns nil." | 2178 | (pcase completion-context |
| 1799 | (python-send-string string) | 2179 | (`pdb python-shell-completion-pdb-string-code) |
| 1800 | (let ((proc (python-proc))) | 2180 | (`import python-shell-completion-module-string-code) |
| 1801 | (with-current-buffer (process-buffer proc) | 2181 | (`default python-shell-completion-string-code) |
| 1802 | (when (python-check-comint-prompt proc) | 2182 | (_ nil))) |
| 1803 | (set (make-local-variable 'python-preoutput-result) nil) | 2183 | (input |
| 1804 | (while (progn | 2184 | (if (eq completion-context 'import) |
| 1805 | (accept-process-output proc 5) | 2185 | (replace-regexp-in-string "^[ \t]+" "" line) |
| 1806 | (null python-preoutput-result))) | 2186 | input))) |
| 1807 | (prog1 python-preoutput-result | 2187 | (and completion-code |
| 1808 | (kill-local-variable 'python-preoutput-result)))))) | 2188 | (> (length input) 0) |
| 1809 | 2189 | (with-current-buffer (process-buffer process) | |
| 1810 | (defun python-check-comint-prompt (&optional proc) | 2190 | (let ((completions (python-shell-send-string-no-output |
| 1811 | "Return non-nil if and only if there's a normal prompt in the inferior buffer. | 2191 | (format completion-code input) process))) |
| 1812 | If there isn't, it's probably not appropriate to send input to return Eldoc | 2192 | (and (> (length completions) 2) |
| 1813 | information etc. If PROC is non-nil, check the buffer for that process." | 2193 | (split-string completions |
| 1814 | (with-current-buffer (process-buffer (or proc (python-proc))) | 2194 | "^'\\|^\"\\|;\\|'$\\|\"$" t))))))) |
| 1815 | (save-excursion | 2195 | |
| 1816 | (save-match-data | 2196 | (defun python-shell-completion-complete-at-point (&optional process) |
| 1817 | (re-search-backward (concat python--prompt-regexp " *\\=") | 2197 | "Perform completion at point in inferior Python. |
| 1818 | nil t))))) | 2198 | Optional argument PROCESS forces completions to be retrieved |
| 2199 | using that one instead of current buffer's process." | ||
| 2200 | (setq process (or process (get-buffer-process (current-buffer)))) | ||
| 2201 | (let* ((start | ||
| 2202 | (save-excursion | ||
| 2203 | (with-syntax-table python-dotty-syntax-table | ||
| 2204 | (let* ((paren-depth (car (syntax-ppss))) | ||
| 2205 | (syntax-string "w_") | ||
| 2206 | (syntax-list (string-to-syntax syntax-string))) | ||
| 2207 | ;; Stop scanning for the beginning of the completion | ||
| 2208 | ;; subject after the char before point matches a | ||
| 2209 | ;; delimiter | ||
| 2210 | (while (member | ||
| 2211 | (car (syntax-after (1- (point)))) syntax-list) | ||
| 2212 | (skip-syntax-backward syntax-string) | ||
| 2213 | (when (or (equal (char-before) ?\)) | ||
| 2214 | (equal (char-before) ?\")) | ||
| 2215 | (forward-char -1)) | ||
| 2216 | (while (or | ||
| 2217 | ;; honor initial paren depth | ||
| 2218 | (> (car (syntax-ppss)) paren-depth) | ||
| 2219 | (python-syntax-context 'string)) | ||
| 2220 | (forward-char -1))) | ||
| 2221 | (point))))) | ||
| 2222 | (end (point))) | ||
| 2223 | (list start end | ||
| 2224 | (completion-table-dynamic | ||
| 2225 | (apply-partially | ||
| 2226 | #'python-shell-completion-get-completions | ||
| 2227 | process (buffer-substring-no-properties | ||
| 2228 | (line-beginning-position) end)))))) | ||
| 2229 | |||
| 2230 | (defun python-shell-completion-complete-or-indent () | ||
| 2231 | "Complete or indent depending on the context. | ||
| 2232 | If content before pointer is all whitespace indent. If not try | ||
| 2233 | to complete." | ||
| 2234 | (interactive) | ||
| 2235 | (if (string-match "^[[:space:]]*$" | ||
| 2236 | (buffer-substring (comint-line-beginning-position) | ||
| 2237 | (point-marker))) | ||
| 2238 | (indent-for-tab-command) | ||
| 2239 | (completion-at-point))) | ||
| 1819 | 2240 | ||
| 1820 | ;; Fixme: Is there anything reasonable we can do with random methods? | ||
| 1821 | ;; (Currently only works with functions.) | ||
| 1822 | (defun python-eldoc-function () | ||
| 1823 | "`eldoc-documentation-function' for Python. | ||
| 1824 | Only works when point is in a function name, not its arg list, for | ||
| 1825 | instance. Assumes an inferior Python is running." | ||
| 1826 | (let ((symbol (with-syntax-table python-dotty-syntax-table | ||
| 1827 | (current-word)))) | ||
| 1828 | ;; This is run from timers, so inhibit-quit tends to be set. | ||
| 1829 | (with-local-quit | ||
| 1830 | ;; First try the symbol we're on. | ||
| 1831 | (or (and symbol | ||
| 1832 | (python-send-receive (format "emacs.eargs(%S, %s)" | ||
| 1833 | symbol python-imports))) | ||
| 1834 | ;; Try moving to symbol before enclosing parens. | ||
| 1835 | (let ((s (syntax-ppss))) | ||
| 1836 | (unless (zerop (car s)) | ||
| 1837 | (when (eq ?\( (char-after (nth 1 s))) | ||
| 1838 | (save-excursion | ||
| 1839 | (goto-char (nth 1 s)) | ||
| 1840 | (skip-syntax-backward "-") | ||
| 1841 | (let ((point (point))) | ||
| 1842 | (skip-chars-backward "a-zA-Z._") | ||
| 1843 | (if (< (point) point) | ||
| 1844 | (python-send-receive | ||
| 1845 | (format "emacs.eargs(%S, %s)" | ||
| 1846 | (buffer-substring-no-properties (point) point) | ||
| 1847 | python-imports)))))))))))) | ||
| 1848 | 2241 | ||
| 1849 | ;;;; Info-look functionality. | 2242 | ;;; PDB Track integration |
| 1850 | 2243 | ||
| 1851 | (declare-function info-lookup-maybe-add-help "info-look" (&rest arg)) | 2244 | (defcustom python-pdbtrack-activate t |
| 2245 | "Non-nil makes python shell enable pdbtracking." | ||
| 2246 | :type 'boolean | ||
| 2247 | :group 'python | ||
| 2248 | :safe 'booleanp) | ||
| 2249 | |||
| 2250 | (defcustom python-pdbtrack-stacktrace-info-regexp | ||
| 2251 | "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()" | ||
| 2252 | "Regular Expression matching stacktrace information. | ||
| 2253 | Used to extract the current line and module being inspected." | ||
| 2254 | :type 'string | ||
| 2255 | :group 'python | ||
| 2256 | :safe 'stringp) | ||
| 2257 | |||
| 2258 | (defvar python-pdbtrack-tracked-buffer nil | ||
| 2259 | "Variable containing the value of the current tracked buffer. | ||
| 2260 | Never set this variable directly, use | ||
| 2261 | `python-pdbtrack-set-tracked-buffer' instead.") | ||
| 2262 | |||
| 2263 | (defvar python-pdbtrack-buffers-to-kill nil | ||
| 2264 | "List of buffers to be deleted after tracking finishes.") | ||
| 2265 | |||
| 2266 | (defun python-pdbtrack-set-tracked-buffer (file-name) | ||
| 2267 | "Set the buffer for FILE-NAME as the tracked buffer. | ||
| 2268 | Internally it uses the `python-pdbtrack-tracked-buffer' variable. | ||
| 2269 | Returns the tracked buffer." | ||
| 2270 | (let ((file-buffer (get-file-buffer file-name))) | ||
| 2271 | (if file-buffer | ||
| 2272 | (setq python-pdbtrack-tracked-buffer file-buffer) | ||
| 2273 | (setq file-buffer (find-file-noselect file-name)) | ||
| 2274 | (when (not (member file-buffer python-pdbtrack-buffers-to-kill)) | ||
| 2275 | (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer))) | ||
| 2276 | file-buffer)) | ||
| 2277 | |||
| 2278 | (defun python-pdbtrack-comint-output-filter-function (output) | ||
| 2279 | "Move overlay arrow to current pdb line in tracked buffer. | ||
| 2280 | Argument OUTPUT is a string with the output from the comint process." | ||
| 2281 | (when (and python-pdbtrack-activate (not (string= output ""))) | ||
| 2282 | (let* ((full-output (ansi-color-filter-apply | ||
| 2283 | (buffer-substring comint-last-input-end (point-max)))) | ||
| 2284 | (line-number) | ||
| 2285 | (file-name | ||
| 2286 | (with-temp-buffer | ||
| 2287 | (insert full-output) | ||
| 2288 | (goto-char (point-min)) | ||
| 2289 | ;; OK, this sucked but now it became a cool hack. The | ||
| 2290 | ;; stacktrace information normally is on the first line | ||
| 2291 | ;; but in some cases (like when doing a step-in) it is | ||
| 2292 | ;; on the second. | ||
| 2293 | (when (or (looking-at python-pdbtrack-stacktrace-info-regexp) | ||
| 2294 | (and | ||
| 2295 | (forward-line) | ||
| 2296 | (looking-at python-pdbtrack-stacktrace-info-regexp))) | ||
| 2297 | (setq line-number (string-to-number | ||
| 2298 | (match-string-no-properties 2))) | ||
| 2299 | (match-string-no-properties 1))))) | ||
| 2300 | (if (and file-name line-number) | ||
| 2301 | (let* ((tracked-buffer | ||
| 2302 | (python-pdbtrack-set-tracked-buffer file-name)) | ||
| 2303 | (shell-buffer (current-buffer)) | ||
| 2304 | (tracked-buffer-window (get-buffer-window tracked-buffer)) | ||
| 2305 | (tracked-buffer-line-pos)) | ||
| 2306 | (with-current-buffer tracked-buffer | ||
| 2307 | (set (make-local-variable 'overlay-arrow-string) "=>") | ||
| 2308 | (set (make-local-variable 'overlay-arrow-position) (make-marker)) | ||
| 2309 | (setq tracked-buffer-line-pos (progn | ||
| 2310 | (goto-char (point-min)) | ||
| 2311 | (forward-line (1- line-number)) | ||
| 2312 | (point-marker))) | ||
| 2313 | (when tracked-buffer-window | ||
| 2314 | (set-window-point | ||
| 2315 | tracked-buffer-window tracked-buffer-line-pos)) | ||
| 2316 | (set-marker overlay-arrow-position tracked-buffer-line-pos)) | ||
| 2317 | (pop-to-buffer tracked-buffer) | ||
| 2318 | (switch-to-buffer-other-window shell-buffer)) | ||
| 2319 | (when python-pdbtrack-tracked-buffer | ||
| 2320 | (with-current-buffer python-pdbtrack-tracked-buffer | ||
| 2321 | (set-marker overlay-arrow-position nil)) | ||
| 2322 | (mapc #'(lambda (buffer) | ||
| 2323 | (ignore-errors (kill-buffer buffer))) | ||
| 2324 | python-pdbtrack-buffers-to-kill) | ||
| 2325 | (setq python-pdbtrack-tracked-buffer nil | ||
| 2326 | python-pdbtrack-buffers-to-kill nil))))) | ||
| 2327 | output) | ||
| 1852 | 2328 | ||
| 1853 | ;;;###autoload | ||
| 1854 | (defun python-after-info-look () | ||
| 1855 | "Set up info-look for Python. | ||
| 1856 | Used with `eval-after-load'." | ||
| 1857 | (let* ((version (let ((s (shell-command-to-string (concat python-command | ||
| 1858 | " -V")))) | ||
| 1859 | (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s) | ||
| 1860 | (match-string 1 s))) | ||
| 1861 | ;; Whether info files have a Python version suffix, e.g. in Debian. | ||
| 1862 | (versioned | ||
| 1863 | (with-temp-buffer | ||
| 1864 | (with-no-warnings (Info-mode)) | ||
| 1865 | (condition-case () | ||
| 1866 | ;; Don't use `info' because it would pop-up a *info* buffer. | ||
| 1867 | (with-no-warnings | ||
| 1868 | (Info-goto-node (format "(python%s-lib)Miscellaneous Index" | ||
| 1869 | version)) | ||
| 1870 | t) | ||
| 1871 | (error nil))))) | ||
| 1872 | (info-lookup-maybe-add-help | ||
| 1873 | :mode 'python-mode | ||
| 1874 | :regexp "[[:alnum:]_]+" | ||
| 1875 | :doc-spec | ||
| 1876 | ;; Fixme: Can this reasonably be made specific to indices with | ||
| 1877 | ;; different rules? Is the order of indices optimal? | ||
| 1878 | ;; (Miscellaneous in -ref first prefers lookup of keywords, for | ||
| 1879 | ;; instance.) | ||
| 1880 | (if versioned | ||
| 1881 | ;; The empty prefix just gets us highlighted terms. | ||
| 1882 | `((,(concat "(python" version "-ref)Miscellaneous Index") nil "") | ||
| 1883 | (,(concat "(python" version "-ref)Module Index" nil "")) | ||
| 1884 | (,(concat "(python" version "-ref)Function-Method-Variable Index" | ||
| 1885 | nil "")) | ||
| 1886 | (,(concat "(python" version "-ref)Class-Exception-Object Index" | ||
| 1887 | nil "")) | ||
| 1888 | (,(concat "(python" version "-lib)Module Index" nil "")) | ||
| 1889 | (,(concat "(python" version "-lib)Class-Exception-Object Index" | ||
| 1890 | nil "")) | ||
| 1891 | (,(concat "(python" version "-lib)Function-Method-Variable Index" | ||
| 1892 | nil "")) | ||
| 1893 | (,(concat "(python" version "-lib)Miscellaneous Index" nil ""))) | ||
| 1894 | '(("(python-ref)Miscellaneous Index" nil "") | ||
| 1895 | ("(python-ref)Module Index" nil "") | ||
| 1896 | ("(python-ref)Function-Method-Variable Index" nil "") | ||
| 1897 | ("(python-ref)Class-Exception-Object Index" nil "") | ||
| 1898 | ("(python-lib)Module Index" nil "") | ||
| 1899 | ("(python-lib)Class-Exception-Object Index" nil "") | ||
| 1900 | ("(python-lib)Function-Method-Variable Index" nil "") | ||
| 1901 | ("(python-lib)Miscellaneous Index" nil "")))))) | ||
| 1902 | (eval-after-load "info-look" '(python-after-info-look)) | ||
| 1903 | 2329 | ||
| 1904 | ;;;; Miscellany. | 2330 | ;;; Symbol completion |
| 1905 | 2331 | ||
| 1906 | (defcustom python-jython-packages '("java" "javax" "org" "com") | 2332 | (defun python-completion-complete-at-point () |
| 1907 | "Packages implying `jython-mode'. | 2333 | "Complete current symbol at point. |
| 1908 | If these are imported near the beginning of the buffer, `python-mode' | 2334 | For this to work the best as possible you should call |
| 1909 | actually punts to `jython-mode'." | 2335 | `python-shell-send-buffer' from time to time so context in |
| 1910 | :type '(repeat string) | 2336 | inferior python process is updated properly." |
| 2337 | (let ((process (python-shell-get-process))) | ||
| 2338 | (if (not process) | ||
| 2339 | (error "Completion needs an inferior Python process running") | ||
| 2340 | (python-shell-completion-complete-at-point process)))) | ||
| 2341 | |||
| 2342 | (add-to-list 'debug-ignored-errors | ||
| 2343 | "^Completion needs an inferior Python process running.") | ||
| 2344 | |||
| 2345 | |||
| 2346 | ;;; Fill paragraph | ||
| 2347 | |||
| 2348 | (defcustom python-fill-comment-function 'python-fill-comment | ||
| 2349 | "Function to fill comments. | ||
| 2350 | This is the function used by `python-fill-paragraph' to | ||
| 2351 | fill comments." | ||
| 2352 | :type 'symbol | ||
| 1911 | :group 'python) | 2353 | :group 'python) |
| 1912 | 2354 | ||
| 1913 | ;; Called from `python-mode', this causes a recursive call of the | 2355 | (defcustom python-fill-string-function 'python-fill-string |
| 1914 | ;; mode. See logic there to break out of the recursion. | 2356 | "Function to fill strings. |
| 1915 | (defun python-maybe-jython () | 2357 | This is the function used by `python-fill-paragraph' to |
| 1916 | "Invoke `jython-mode' if the buffer appears to contain Jython code. | 2358 | fill strings." |
| 1917 | The criterion is either a match for `jython-mode' via | 2359 | :type 'symbol |
| 1918 | `interpreter-mode-alist' or an import of a module from the list | 2360 | :group 'python) |
| 1919 | `python-jython-packages'." | ||
| 1920 | ;; The logic is taken from python-mode.el. | ||
| 1921 | (save-excursion | ||
| 1922 | (save-restriction | ||
| 1923 | (widen) | ||
| 1924 | (goto-char (point-min)) | ||
| 1925 | (let ((interpreter (if (looking-at auto-mode-interpreter-regexp) | ||
| 1926 | (match-string 2)))) | ||
| 1927 | (if (and interpreter (eq 'jython-mode | ||
| 1928 | (cdr (assoc (file-name-nondirectory | ||
| 1929 | interpreter) | ||
| 1930 | interpreter-mode-alist)))) | ||
| 1931 | (jython-mode) | ||
| 1932 | (if (catch 'done | ||
| 1933 | (while (re-search-forward | ||
| 1934 | (rx line-start (or "import" "from") (1+ space) | ||
| 1935 | (group (1+ (not (any " \t\n."))))) | ||
| 1936 | (+ (point-min) 10000) ; Probably not worth customizing. | ||
| 1937 | t) | ||
| 1938 | (if (member (match-string 1) python-jython-packages) | ||
| 1939 | (throw 'done t)))) | ||
| 1940 | (jython-mode))))))) | ||
| 1941 | 2361 | ||
| 1942 | (defun python-fill-paragraph (&optional justify) | 2362 | (defcustom python-fill-decorator-function 'python-fill-decorator |
| 1943 | "`fill-paragraph-function' handling multi-line strings and possibly comments. | 2363 | "Function to fill decorators. |
| 1944 | If any of the current line is in or at the end of a multi-line string, | 2364 | This is the function used by `python-fill-paragraph' to |
| 1945 | fill the string or the paragraph of it that point is in, preserving | 2365 | fill decorators." |
| 1946 | the string's indentation." | 2366 | :type 'symbol |
| 1947 | (interactive "P") | 2367 | :group 'python) |
| 1948 | (or (fill-comment-paragraph justify) | ||
| 1949 | (save-excursion | ||
| 1950 | (end-of-line) | ||
| 1951 | (let* ((syntax (syntax-ppss)) | ||
| 1952 | (orig (point)) | ||
| 1953 | start end) | ||
| 1954 | (cond ((nth 4 syntax) ; comment. fixme: loses with trailing one | ||
| 1955 | (let (fill-paragraph-function) | ||
| 1956 | (fill-paragraph justify))) | ||
| 1957 | ;; The `paragraph-start' and `paragraph-separate' | ||
| 1958 | ;; variables don't allow us to delimit the last | ||
| 1959 | ;; paragraph in a multi-line string properly, so narrow | ||
| 1960 | ;; to the string and then fill around (the end of) the | ||
| 1961 | ;; current line. | ||
| 1962 | ((eq t (nth 3 syntax)) ; in fenced string | ||
| 1963 | (goto-char (nth 8 syntax)) ; string start | ||
| 1964 | (setq start (line-beginning-position)) | ||
| 1965 | (setq end (condition-case () ; for unbalanced quotes | ||
| 1966 | (progn (forward-sexp) | ||
| 1967 | (- (point) 3)) | ||
| 1968 | (error (point-max))))) | ||
| 1969 | ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced string | ||
| 1970 | (forward-char) | ||
| 1971 | (setq end (point)) | ||
| 1972 | (condition-case () | ||
| 1973 | (progn (backward-sexp) | ||
| 1974 | (setq start (line-beginning-position))) | ||
| 1975 | (error nil)))) | ||
| 1976 | (when end | ||
| 1977 | (save-restriction | ||
| 1978 | (narrow-to-region start end) | ||
| 1979 | (goto-char orig) | ||
| 1980 | ;; Avoid losing leading and trailing newlines in doc | ||
| 1981 | ;; strings written like: | ||
| 1982 | ;; """ | ||
| 1983 | ;; ... | ||
| 1984 | ;; """ | ||
| 1985 | (let ((paragraph-separate | ||
| 1986 | ;; Note that the string could be part of an | ||
| 1987 | ;; expression, so it can have preceding and | ||
| 1988 | ;; trailing non-whitespace. | ||
| 1989 | (concat | ||
| 1990 | (rx (or | ||
| 1991 | ;; Opening triple quote without following text. | ||
| 1992 | (and (* nonl) | ||
| 1993 | (group (syntax string-delimiter)) | ||
| 1994 | (repeat 2 (backref 1)) | ||
| 1995 | ;; Fixme: Not sure about including | ||
| 1996 | ;; trailing whitespace. | ||
| 1997 | (* (any " \t")) | ||
| 1998 | eol) | ||
| 1999 | ;; Closing trailing quote without preceding text. | ||
| 2000 | (and (group (any ?\" ?')) (backref 2) | ||
| 2001 | (syntax string-delimiter)))) | ||
| 2002 | "\\(?:" paragraph-separate "\\)")) | ||
| 2003 | fill-paragraph-function) | ||
| 2004 | (fill-paragraph justify))))))) t) | ||
| 2005 | |||
| 2006 | (defun python-shift-left (start end &optional count) | ||
| 2007 | "Shift lines in region COUNT (the prefix arg) columns to the left. | ||
| 2008 | COUNT defaults to `python-indent'. If region isn't active, just shift | ||
| 2009 | current line. The region shifted includes the lines in which START and | ||
| 2010 | END lie. It is an error if any lines in the region are indented less than | ||
| 2011 | COUNT columns." | ||
| 2012 | (interactive | ||
| 2013 | (if mark-active | ||
| 2014 | (list (region-beginning) (region-end) current-prefix-arg) | ||
| 2015 | (list (line-beginning-position) (line-end-position) current-prefix-arg))) | ||
| 2016 | (if count | ||
| 2017 | (setq count (prefix-numeric-value count)) | ||
| 2018 | (setq count python-indent)) | ||
| 2019 | (when (> count 0) | ||
| 2020 | (save-excursion | ||
| 2021 | (goto-char start) | ||
| 2022 | (while (< (point) end) | ||
| 2023 | (if (and (< (current-indentation) count) | ||
| 2024 | (not (looking-at "[ \t]*$"))) | ||
| 2025 | (error "Can't shift all lines enough")) | ||
| 2026 | (forward-line)) | ||
| 2027 | (indent-rigidly start end (- count))))) | ||
| 2028 | 2368 | ||
| 2029 | (add-to-list 'debug-ignored-errors "^Can't shift all lines enough") | 2369 | (defcustom python-fill-paren-function 'python-fill-paren |
| 2370 | "Function to fill parens. | ||
| 2371 | This is the function used by `python-fill-paragraph' to | ||
| 2372 | fill parens." | ||
| 2373 | :type 'symbol | ||
| 2374 | :group 'python) | ||
| 2030 | 2375 | ||
| 2031 | (defun python-shift-right (start end &optional count) | 2376 | (defcustom python-fill-docstring-style 'pep-257 |
| 2032 | "Shift lines in region COUNT (the prefix arg) columns to the right. | 2377 | "Style used to fill docstrings. |
| 2033 | COUNT defaults to `python-indent'. If region isn't active, just shift | 2378 | This affects `python-fill-string' behavior with regards to |
| 2034 | current line. The region shifted includes the lines in which START and | 2379 | triple quotes positioning. |
| 2035 | END lie." | ||
| 2036 | (interactive | ||
| 2037 | (if mark-active | ||
| 2038 | (list (region-beginning) (region-end) current-prefix-arg) | ||
| 2039 | (list (line-beginning-position) (line-end-position) current-prefix-arg))) | ||
| 2040 | (if count | ||
| 2041 | (setq count (prefix-numeric-value count)) | ||
| 2042 | (setq count python-indent)) | ||
| 2043 | (indent-rigidly start end count)) | ||
| 2044 | |||
| 2045 | (defun python-outline-level () | ||
| 2046 | "`outline-level' function for Python mode. | ||
| 2047 | The level is the number of `python-indent' steps of indentation | ||
| 2048 | of current line." | ||
| 2049 | (1+ (/ (current-indentation) python-indent))) | ||
| 2050 | |||
| 2051 | ;; Fixme: Consider top-level assignments, imports, &c. | ||
| 2052 | (defun python-current-defun (&optional length-limit) | ||
| 2053 | "`add-log-current-defun-function' for Python." | ||
| 2054 | (save-excursion | ||
| 2055 | ;; Move up the tree of nested `class' and `def' blocks until we | ||
| 2056 | ;; get to zero indentation, accumulating the defined names. | ||
| 2057 | (let ((accum) | ||
| 2058 | (length -1)) | ||
| 2059 | (catch 'done | ||
| 2060 | (while (or (null length-limit) | ||
| 2061 | (null (cdr accum)) | ||
| 2062 | (< length length-limit)) | ||
| 2063 | (let ((started-from (point))) | ||
| 2064 | (python-beginning-of-block) | ||
| 2065 | (end-of-line) | ||
| 2066 | (beginning-of-defun) | ||
| 2067 | (when (= (point) started-from) | ||
| 2068 | (throw 'done nil))) | ||
| 2069 | (when (looking-at (rx (0+ space) (or "def" "class") (1+ space) | ||
| 2070 | (group (1+ (or word (syntax symbol)))))) | ||
| 2071 | (push (match-string 1) accum) | ||
| 2072 | (setq length (+ length 1 (length (car accum))))) | ||
| 2073 | (when (= (current-indentation) 0) | ||
| 2074 | (throw 'done nil)))) | ||
| 2075 | (when accum | ||
| 2076 | (when (and length-limit (> length length-limit)) | ||
| 2077 | (setcar accum "..")) | ||
| 2078 | (mapconcat 'identity accum "."))))) | ||
| 2079 | |||
| 2080 | (defun python-mark-block () | ||
| 2081 | "Mark the block around point. | ||
| 2082 | Uses `python-beginning-of-block', `python-end-of-block'." | ||
| 2083 | (interactive) | ||
| 2084 | (push-mark) | ||
| 2085 | (python-beginning-of-block) | ||
| 2086 | (push-mark (point) nil t) | ||
| 2087 | (python-end-of-block) | ||
| 2088 | (exchange-point-and-mark)) | ||
| 2089 | |||
| 2090 | ;; Fixme: Provide a find-function-like command to find source of a | ||
| 2091 | ;; definition (separate from BicycleRepairMan). Complicated by | ||
| 2092 | ;; finding the right qualified name. | ||
| 2093 | |||
| 2094 | ;;;; Completion. | ||
| 2095 | |||
| 2096 | ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-01/msg00076.html | ||
| 2097 | (defvar python-imports "None" | ||
| 2098 | "String of top-level import statements updated by `python-find-imports'.") | ||
| 2099 | (make-variable-buffer-local 'python-imports) | ||
| 2100 | |||
| 2101 | ;; Fixme: Should font-lock try to run this when it deals with an import? | ||
| 2102 | ;; Maybe not a good idea if it gets run multiple times when the | ||
| 2103 | ;; statement is being edited, and is more likely to end up with | ||
| 2104 | ;; something syntactically incorrect. | ||
| 2105 | ;; However, what we should do is to trundle up the block tree from point | ||
| 2106 | ;; to extract imports that appear to be in scope, and add those. | ||
| 2107 | (defun python-find-imports () | ||
| 2108 | "Find top-level imports, updating `python-imports'." | ||
| 2109 | (interactive) | ||
| 2110 | (save-excursion | ||
| 2111 | (let (lines) | ||
| 2112 | (goto-char (point-min)) | ||
| 2113 | (while (re-search-forward "^import\\>\\|^from\\>" nil t) | ||
| 2114 | (unless (syntax-ppss-context (syntax-ppss)) | ||
| 2115 | (let ((start (line-beginning-position))) | ||
| 2116 | ;; Skip over continued lines. | ||
| 2117 | (while (and (eq ?\\ (char-before (line-end-position))) | ||
| 2118 | (= 0 (forward-line 1))) | ||
| 2119 | t) | ||
| 2120 | (push (buffer-substring start (line-beginning-position 2)) | ||
| 2121 | lines)))) | ||
| 2122 | (setq python-imports | ||
| 2123 | (if lines | ||
| 2124 | (apply #'concat | ||
| 2125 | ;; This is probably best left out since you're unlikely to need the | ||
| 2126 | ;; doc for a function in the buffer and the import will lose if the | ||
| 2127 | ;; Python sub-process' working directory isn't the same as the | ||
| 2128 | ;; buffer's. | ||
| 2129 | ;; (if buffer-file-name | ||
| 2130 | ;; (concat | ||
| 2131 | ;; "import " | ||
| 2132 | ;; (file-name-sans-extension | ||
| 2133 | ;; (file-name-nondirectory buffer-file-name)))) | ||
| 2134 | (nreverse lines)) | ||
| 2135 | "None")) | ||
| 2136 | (when lines | ||
| 2137 | (set-text-properties 0 (length python-imports) nil python-imports) | ||
| 2138 | ;; The output ends up in the wrong place if the string we | ||
| 2139 | ;; send contains newlines (from the imports). | ||
| 2140 | (setq python-imports | ||
| 2141 | (replace-regexp-in-string "\n" "\\n" | ||
| 2142 | (format "%S" python-imports) t t)))))) | ||
| 2143 | |||
| 2144 | ;; Fixme: This fails the first time if the sub-process isn't already | ||
| 2145 | ;; running. Presumably a timing issue with i/o to the process. | ||
| 2146 | (defun python-symbol-completions (symbol) | ||
| 2147 | "Return a list of completions of the string SYMBOL from Python process. | ||
| 2148 | The list is sorted. | ||
| 2149 | Uses `python-imports' to load modules against which to complete." | ||
| 2150 | (when (stringp symbol) | ||
| 2151 | (let ((completions | ||
| 2152 | (condition-case () | ||
| 2153 | (car (read-from-string | ||
| 2154 | (python-send-receive | ||
| 2155 | (format "emacs.complete(%S,%s)" | ||
| 2156 | (substring-no-properties symbol) | ||
| 2157 | python-imports)))) | ||
| 2158 | (error nil)))) | ||
| 2159 | (sort | ||
| 2160 | ;; We can get duplicates from the above -- don't know why. | ||
| 2161 | (delete-dups completions) | ||
| 2162 | #'string<)))) | ||
| 2163 | |||
| 2164 | (defun python-completion-at-point () | ||
| 2165 | (let ((end (point)) | ||
| 2166 | (start (save-excursion | ||
| 2167 | (and (re-search-backward | ||
| 2168 | (rx (or buffer-start (regexp "[^[:alnum:]._]")) | ||
| 2169 | (group (1+ (regexp "[[:alnum:]._]"))) point) | ||
| 2170 | nil t) | ||
| 2171 | (match-beginning 1))))) | ||
| 2172 | (when start | ||
| 2173 | (list start end | ||
| 2174 | (completion-table-dynamic 'python-symbol-completions))))) | ||
| 2175 | |||
| 2176 | ;;;; FFAP support | ||
| 2177 | 2380 | ||
| 2178 | (defun python-module-path (module) | 2381 | Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN, |
| 2179 | "Function for `ffap-alist' to return path to MODULE." | 2382 | SYMMETRIC, and NIL. A value of NIL won't care about quotes |
| 2180 | (python-send-receive (format "emacs.modpath (%S)" module))) | 2383 | position and will treat docstrings a normal string, any other |
| 2384 | value may result in one of the following docstring styles: | ||
| 2181 | 2385 | ||
| 2182 | (eval-after-load "ffap" | 2386 | DJANGO: |
| 2183 | '(push '(python-mode . python-module-path) ffap-alist)) | ||
| 2184 | |||
| 2185 | ;;;; Find-function support | ||
| 2186 | 2387 | ||
| 2187 | ;; Fixme: key binding? | 2388 | \"\"\" |
| 2389 | Process foo, return bar. | ||
| 2390 | \"\"\" | ||
| 2188 | 2391 | ||
| 2189 | (defun python-find-function (name) | 2392 | \"\"\" |
| 2190 | "Find source of definition of function NAME. | 2393 | Process foo, return bar. |
| 2191 | Interactively, prompt for name." | 2394 | |
| 2192 | (interactive | 2395 | If processing fails throw ProcessingError. |
| 2193 | (let ((symbol (with-syntax-table python-dotty-syntax-table | 2396 | \"\"\" |
| 2194 | (current-word))) | 2397 | |
| 2195 | (enable-recursive-minibuffers t)) | 2398 | ONETWO: |
| 2196 | (list (read-string (if symbol | 2399 | |
| 2197 | (format "Find location of (default %s): " symbol) | 2400 | \"\"\"Process foo, return bar.\"\"\" |
| 2198 | "Find location of: ") | 2401 | |
| 2199 | nil nil symbol)))) | 2402 | \"\"\" |
| 2200 | (unless python-imports | 2403 | Process foo, return bar. |
| 2201 | (error "Not called from buffer visiting Python file")) | 2404 | |
| 2202 | (let* ((loc (python-send-receive (format "emacs.location_of (%S, %s)" | 2405 | If processing fails throw ProcessingError. |
| 2203 | name python-imports))) | 2406 | |
| 2204 | (loc (car (read-from-string loc))) | 2407 | \"\"\" |
| 2205 | (file (car loc)) | 2408 | |
| 2206 | (line (cdr loc))) | 2409 | PEP-257: |
| 2207 | (unless file (error "Don't know where `%s' is defined" name)) | 2410 | |
| 2208 | (pop-to-buffer (find-file-noselect file)) | 2411 | \"\"\"Process foo, return bar.\"\"\" |
| 2209 | (when (integerp line) | 2412 | |
| 2413 | \"\"\"Process foo, return bar. | ||
| 2414 | |||
| 2415 | If processing fails throw ProcessingError. | ||
| 2416 | |||
| 2417 | \"\"\" | ||
| 2418 | |||
| 2419 | PEP-257-NN: | ||
| 2420 | |||
| 2421 | \"\"\"Process foo, return bar.\"\"\" | ||
| 2422 | |||
| 2423 | \"\"\"Process foo, return bar. | ||
| 2424 | |||
| 2425 | If processing fails throw ProcessingError. | ||
| 2426 | \"\"\" | ||
| 2427 | |||
| 2428 | SYMMETRIC: | ||
| 2429 | |||
| 2430 | \"\"\"Process foo, return bar.\"\"\" | ||
| 2431 | |||
| 2432 | \"\"\" | ||
| 2433 | Process foo, return bar. | ||
| 2434 | |||
| 2435 | If processing fails throw ProcessingError. | ||
| 2436 | \"\"\"" | ||
| 2437 | :type '(choice | ||
| 2438 | (const :tag "Don't format docstrings" nil) | ||
| 2439 | (const :tag "Django's coding standards style." django) | ||
| 2440 | (const :tag "One newline and start and Two at end style." onetwo) | ||
| 2441 | (const :tag "PEP-257 with 2 newlines at end of string." pep-257) | ||
| 2442 | (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn) | ||
| 2443 | (const :tag "Symmetric style." symmetric)) | ||
| 2444 | :group 'python | ||
| 2445 | :safe (lambda (val) | ||
| 2446 | (memq val '(django onetwo pep-257 pep-257-nn symmetric nil)))) | ||
| 2447 | |||
| 2448 | (defun python-fill-paragraph (&optional justify) | ||
| 2449 | "`fill-paragraph-function' handling multi-line strings and possibly comments. | ||
| 2450 | If any of the current line is in or at the end of a multi-line string, | ||
| 2451 | fill the string or the paragraph of it that point is in, preserving | ||
| 2452 | the string's indentation. | ||
| 2453 | Optional argument JUSTIFY defines if the paragraph should be justified." | ||
| 2454 | (interactive "P") | ||
| 2455 | (save-excursion | ||
| 2456 | (cond | ||
| 2457 | ;; Comments | ||
| 2458 | ((python-syntax-context 'comment) | ||
| 2459 | (funcall python-fill-comment-function justify)) | ||
| 2460 | ;; Strings/Docstrings | ||
| 2461 | ((save-excursion (or (python-syntax-context 'string) | ||
| 2462 | (equal (string-to-syntax "|") | ||
| 2463 | (syntax-after (point))))) | ||
| 2464 | (funcall python-fill-string-function justify)) | ||
| 2465 | ;; Decorators | ||
| 2466 | ((equal (char-after (save-excursion | ||
| 2467 | (python-nav-beginning-of-statement))) ?@) | ||
| 2468 | (funcall python-fill-decorator-function justify)) | ||
| 2469 | ;; Parens | ||
| 2470 | ((or (python-syntax-context 'paren) | ||
| 2471 | (looking-at (python-rx open-paren)) | ||
| 2472 | (save-excursion | ||
| 2473 | (skip-syntax-forward "^(" (line-end-position)) | ||
| 2474 | (looking-at (python-rx open-paren)))) | ||
| 2475 | (funcall python-fill-paren-function justify)) | ||
| 2476 | (t t)))) | ||
| 2477 | |||
| 2478 | (defun python-fill-comment (&optional justify) | ||
| 2479 | "Comment fill function for `python-fill-paragraph'. | ||
| 2480 | JUSTIFY should be used (if applicable) as in `fill-paragraph'." | ||
| 2481 | (fill-comment-paragraph justify)) | ||
| 2482 | |||
| 2483 | (defun python-fill-string (&optional justify) | ||
| 2484 | "String fill function for `python-fill-paragraph'. | ||
| 2485 | JUSTIFY should be used (if applicable) as in `fill-paragraph'." | ||
| 2486 | (let* ((marker (point-marker)) | ||
| 2487 | (str-start-pos | ||
| 2488 | (let ((m (make-marker))) | ||
| 2489 | (setf (marker-position m) | ||
| 2490 | (or (python-syntax-context 'string) | ||
| 2491 | (and (equal (string-to-syntax "|") | ||
| 2492 | (syntax-after (point))) | ||
| 2493 | (point)))) m)) | ||
| 2494 | (num-quotes (python-syntax-count-quotes | ||
| 2495 | (char-after str-start-pos) str-start-pos)) | ||
| 2496 | (str-end-pos | ||
| 2497 | (save-excursion | ||
| 2498 | (goto-char (+ str-start-pos num-quotes)) | ||
| 2499 | (or (re-search-forward (rx (syntax string-delimiter)) nil t) | ||
| 2500 | (goto-char (point-max))) | ||
| 2501 | (point-marker))) | ||
| 2502 | (multi-line-p | ||
| 2503 | ;; Docstring styles may vary for oneliners and multi-liners. | ||
| 2504 | (> (count-matches "\n" str-start-pos str-end-pos) 0)) | ||
| 2505 | (delimiters-style | ||
| 2506 | (pcase python-fill-docstring-style | ||
| 2507 | ;; delimiters-style is a cons cell with the form | ||
| 2508 | ;; (START-NEWLINES . END-NEWLINES). When any of the sexps | ||
| 2509 | ;; is NIL means to not add any newlines for start or end | ||
| 2510 | ;; of docstring. See `python-fill-docstring-style' for a | ||
| 2511 | ;; graphic idea of each style. | ||
| 2512 | (`django (cons 1 1)) | ||
| 2513 | (`onetwo (and multi-line-p (cons 1 2))) | ||
| 2514 | (`pep-257 (and multi-line-p (cons nil 2))) | ||
| 2515 | (`pep-257-nn (and multi-line-p (cons nil 1))) | ||
| 2516 | (`symmetric (and multi-line-p (cons 1 1))))) | ||
| 2517 | (docstring-p (save-excursion | ||
| 2518 | ;; Consider docstrings those strings which | ||
| 2519 | ;; start on a line by themselves. | ||
| 2520 | (python-nav-beginning-of-statement) | ||
| 2521 | (and (= (point) str-start-pos)))) | ||
| 2522 | (fill-paragraph-function)) | ||
| 2523 | (save-restriction | ||
| 2524 | (narrow-to-region str-start-pos str-end-pos) | ||
| 2525 | (fill-paragraph justify)) | ||
| 2526 | (save-excursion | ||
| 2527 | (when (and docstring-p python-fill-docstring-style) | ||
| 2528 | ;; Add the number of newlines indicated by the selected style | ||
| 2529 | ;; at the start of the docstring. | ||
| 2530 | (goto-char (+ str-start-pos num-quotes)) | ||
| 2531 | (delete-region (point) (progn | ||
| 2532 | (skip-syntax-forward "> ") | ||
| 2533 | (point))) | ||
| 2534 | (and (car delimiters-style) | ||
| 2535 | (or (newline (car delimiters-style)) t) | ||
| 2536 | ;; Indent only if a newline is added. | ||
| 2537 | (indent-according-to-mode)) | ||
| 2538 | ;; Add the number of newlines indicated by the selected style | ||
| 2539 | ;; at the end of the docstring. | ||
| 2540 | (goto-char (if (not (= str-end-pos (point-max))) | ||
| 2541 | (- str-end-pos num-quotes) | ||
| 2542 | str-end-pos)) | ||
| 2543 | (delete-region (point) (progn | ||
| 2544 | (skip-syntax-backward "> ") | ||
| 2545 | (point))) | ||
| 2546 | (and (cdr delimiters-style) | ||
| 2547 | ;; Add newlines only if string ends. | ||
| 2548 | (not (= str-end-pos (point-max))) | ||
| 2549 | (or (newline (cdr delimiters-style)) t) | ||
| 2550 | ;; Again indent only if a newline is added. | ||
| 2551 | (indent-according-to-mode))))) t) | ||
| 2552 | |||
| 2553 | (defun python-fill-decorator (&optional justify) | ||
| 2554 | "Decorator fill function for `python-fill-paragraph'. | ||
| 2555 | JUSTIFY should be used (if applicable) as in `fill-paragraph'." | ||
| 2556 | t) | ||
| 2557 | |||
| 2558 | (defun python-fill-paren (&optional justify) | ||
| 2559 | "Paren fill function for `python-fill-paragraph'. | ||
| 2560 | JUSTIFY should be used (if applicable) as in `fill-paragraph'." | ||
| 2561 | (save-restriction | ||
| 2562 | (narrow-to-region (progn | ||
| 2563 | (while (python-syntax-context 'paren) | ||
| 2564 | (goto-char (1- (point-marker)))) | ||
| 2565 | (point-marker) | ||
| 2566 | (line-beginning-position)) | ||
| 2567 | (progn | ||
| 2568 | (when (not (python-syntax-context 'paren)) | ||
| 2569 | (end-of-line) | ||
| 2570 | (when (not (python-syntax-context 'paren)) | ||
| 2571 | (skip-syntax-backward "^)"))) | ||
| 2572 | (while (python-syntax-context 'paren) | ||
| 2573 | (goto-char (1+ (point-marker)))) | ||
| 2574 | (point-marker))) | ||
| 2575 | (let ((paragraph-start "\f\\|[ \t]*$") | ||
| 2576 | (paragraph-separate ",") | ||
| 2577 | (fill-paragraph-function)) | ||
| 2210 | (goto-char (point-min)) | 2578 | (goto-char (point-min)) |
| 2211 | (forward-line (1- line))))) | 2579 | (fill-paragraph justify)) |
| 2580 | (while (not (eobp)) | ||
| 2581 | (forward-line 1) | ||
| 2582 | (python-indent-line) | ||
| 2583 | (goto-char (line-end-position)))) t) | ||
| 2584 | |||
| 2212 | 2585 | ||
| 2213 | ;;;; Skeletons | 2586 | ;;; Skeletons |
| 2214 | 2587 | ||
| 2215 | (defcustom python-use-skeletons nil | 2588 | (defcustom python-skeleton-autoinsert nil |
| 2216 | "Non-nil means template skeletons will be automagically inserted. | 2589 | "Non-nil means template skeletons will be automagically inserted. |
| 2217 | This happens when pressing \"if<SPACE>\", for example, to prompt for | 2590 | This happens when pressing \"if<SPACE>\", for example, to prompt for |
| 2218 | the if condition." | 2591 | the if condition." |
| 2219 | :type 'boolean | 2592 | :type 'boolean |
| 2220 | :group 'python) | 2593 | :group 'python |
| 2594 | :safe 'booleanp) | ||
| 2595 | |||
| 2596 | (define-obsolete-variable-alias | ||
| 2597 | 'python-use-skeletons 'python-skeleton-autoinsert "24.3") | ||
| 2598 | |||
| 2599 | (defvar python-skeleton-available '() | ||
| 2600 | "Internal list of available skeletons.") | ||
| 2221 | 2601 | ||
| 2222 | (define-abbrev-table 'python-mode-abbrev-table () | 2602 | (define-abbrev-table 'python-mode-abbrev-table () |
| 2223 | "Abbrev table for Python mode." | 2603 | "Abbrev table for Python mode." |
| @@ -2225,507 +2605,668 @@ the if condition." | |||
| 2225 | ;; Allow / inside abbrevs. | 2605 | ;; Allow / inside abbrevs. |
| 2226 | :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*" | 2606 | :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*" |
| 2227 | ;; Only expand in code. | 2607 | ;; Only expand in code. |
| 2228 | :enable-function (lambda () (not (python-in-string/comment)))) | 2608 | :enable-function (lambda () |
| 2229 | 2609 | (and | |
| 2230 | (eval-when-compile | 2610 | (not (python-syntax-comment-or-string-p)) |
| 2231 | ;; Define a user-level skeleton and add it to the abbrev table. | 2611 | python-skeleton-autoinsert))) |
| 2232 | (defmacro def-python-skeleton (name &rest elements) | 2612 | |
| 2613 | (defmacro python-skeleton-define (name doc &rest skel) | ||
| 2614 | "Define a `python-mode' skeleton using NAME DOC and SKEL. | ||
| 2615 | The skeleton will be bound to python-skeleton-NAME and will | ||
| 2616 | be added to `python-mode-abbrev-table'." | ||
| 2233 | (declare (indent 2)) | 2617 | (declare (indent 2)) |
| 2234 | (let* ((name (symbol-name name)) | 2618 | (let* ((name (symbol-name name)) |
| 2235 | (function (intern (concat "python-insert-" name)))) | 2619 | (function-name (intern (concat "python-skeleton-" name)))) |
| 2236 | `(progn | 2620 | `(progn |
| 2237 | ;; Usual technique for inserting a skeleton, but expand | 2621 | (define-abbrev python-mode-abbrev-table ,name "" ',function-name |
| 2238 | ;; to the original abbrev instead if in a comment or string. | 2622 | :system t) |
| 2239 | (when python-use-skeletons | 2623 | (setq python-skeleton-available |
| 2240 | (define-abbrev python-mode-abbrev-table ,name "" | 2624 | (cons ',function-name python-skeleton-available)) |
| 2241 | ',function | 2625 | (define-skeleton ,function-name |
| 2242 | nil t)) ; system abbrev | 2626 | ,(or doc |
| 2243 | (define-skeleton ,function | 2627 | (format "Insert %s statement." name)) |
| 2244 | ,(format "Insert Python \"%s\" template." name) | 2628 | ,@skel)))) |
| 2245 | ,@elements))))) | 2629 | |
| 2246 | 2630 | (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel) | |
| 2247 | ;; From `skeleton-further-elements' set below: | 2631 | "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL. |
| 2248 | ;; `<': outdent a level; | 2632 | The skeleton will be bound to python-skeleton-NAME." |
| 2249 | ;; `^': delete indentation on current line and also previous newline. | 2633 | (declare (indent 2)) |
| 2250 | ;; Not quite like `delete-indentation'. Assumes point is at | 2634 | (let* ((name (symbol-name name)) |
| 2251 | ;; beginning of indentation. | 2635 | (function-name (intern (concat "python-skeleton--" name))) |
| 2252 | 2636 | (msg (format | |
| 2253 | (def-python-skeleton if | 2637 | "Add '%s' clause? " name))) |
| 2638 | (when (not skel) | ||
| 2639 | (setq skel | ||
| 2640 | `(< ,(format "%s:" name) \n \n | ||
| 2641 | > _ \n))) | ||
| 2642 | `(define-skeleton ,function-name | ||
| 2643 | ,(or doc | ||
| 2644 | (format "Auxiliary skeleton for %s statement." name)) | ||
| 2645 | nil | ||
| 2646 | (unless (y-or-n-p ,msg) | ||
| 2647 | (signal 'quit t)) | ||
| 2648 | ,@skel))) | ||
| 2649 | |||
| 2650 | (python-define-auxiliary-skeleton else nil) | ||
| 2651 | |||
| 2652 | (python-define-auxiliary-skeleton except nil) | ||
| 2653 | |||
| 2654 | (python-define-auxiliary-skeleton finally nil) | ||
| 2655 | |||
| 2656 | (python-skeleton-define if nil | ||
| 2254 | "Condition: " | 2657 | "Condition: " |
| 2255 | "if " str ":" \n | 2658 | "if " str ":" \n |
| 2256 | > -1 ; Fixme: I don't understand the spurious space this removes. | ||
| 2257 | _ \n | 2659 | _ \n |
| 2258 | ("other condition, %s: " | 2660 | ("other condition, %s: " |
| 2259 | < ; Avoid wrong indentation after block opening. | 2661 | < |
| 2260 | "elif " str ":" \n | 2662 | "elif " str ":" \n |
| 2261 | > _ \n nil) | 2663 | > _ \n nil) |
| 2262 | '(python-else) | ^) | 2664 | '(python-skeleton--else) | ^) |
| 2263 | 2665 | ||
| 2264 | (define-skeleton python-else | 2666 | (python-skeleton-define while nil |
| 2265 | "Auxiliary skeleton." | ||
| 2266 | nil | ||
| 2267 | (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) ")) | ||
| 2268 | (signal 'quit t)) | ||
| 2269 | < "else:" \n | ||
| 2270 | > _ \n) | ||
| 2271 | |||
| 2272 | (def-python-skeleton while | ||
| 2273 | "Condition: " | 2667 | "Condition: " |
| 2274 | "while " str ":" \n | 2668 | "while " str ":" \n |
| 2275 | > -1 _ \n | 2669 | > _ \n |
| 2276 | '(python-else) | ^) | 2670 | '(python-skeleton--else) | ^) |
| 2277 | 2671 | ||
| 2278 | (def-python-skeleton for | 2672 | (python-skeleton-define for nil |
| 2279 | "Target, %s: " | 2673 | "Iteration spec: " |
| 2280 | "for " str " in " (skeleton-read "Expression, %s: ") ":" \n | 2674 | "for " str ":" \n |
| 2281 | > -1 _ \n | 2675 | > _ \n |
| 2282 | '(python-else) | ^) | 2676 | '(python-skeleton--else) | ^) |
| 2283 | 2677 | ||
| 2284 | (def-python-skeleton try/except | 2678 | (python-skeleton-define try nil |
| 2285 | nil | 2679 | nil |
| 2286 | "try:" \n | 2680 | "try:" \n |
| 2287 | > -1 _ \n | 2681 | > _ \n |
| 2288 | ("Exception, %s: " | 2682 | ("Exception, %s: " |
| 2289 | < "except " str '(python-target) ":" \n | 2683 | < |
| 2684 | "except " str ":" \n | ||
| 2290 | > _ \n nil) | 2685 | > _ \n nil) |
| 2291 | < "except:" \n | 2686 | resume: |
| 2292 | > _ \n | 2687 | '(python-skeleton--except) |
| 2293 | '(python-else) | ^) | 2688 | '(python-skeleton--else) |
| 2294 | 2689 | '(python-skeleton--finally) | ^) | |
| 2295 | (define-skeleton python-target | 2690 | |
| 2296 | "Auxiliary skeleton." | 2691 | (python-skeleton-define def nil |
| 2297 | "Target, %s: " ", " str | -2) | 2692 | "Function name: " |
| 2298 | 2693 | "def " str " (" ("Parameter, %s: " | |
| 2299 | (def-python-skeleton try/finally | 2694 | (unless (equal ?\( (char-before)) ", ") |
| 2300 | nil | 2695 | str) "):" \n |
| 2301 | "try:" \n | 2696 | "\"\"\"" - "\"\"\"" \n |
| 2302 | > -1 _ \n | 2697 | > _ \n) |
| 2303 | < "finally:" \n | 2698 | |
| 2304 | > _ \n) | 2699 | (python-skeleton-define class nil |
| 2305 | 2700 | "Class name: " | |
| 2306 | (def-python-skeleton def | ||
| 2307 | "Name: " | ||
| 2308 | "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ") | ||
| 2309 | str) "):" \n | ||
| 2310 | "\"\"\"" - "\"\"\"" \n ; Fixme: extra space inserted -- why?). | ||
| 2311 | > _ \n) | ||
| 2312 | |||
| 2313 | (def-python-skeleton class | ||
| 2314 | "Name: " | ||
| 2315 | "class " str " (" ("Inheritance, %s: " | 2701 | "class " str " (" ("Inheritance, %s: " |
| 2316 | (unless (equal ?\( (char-before)) ", ") | 2702 | (unless (equal ?\( (char-before)) ", ") |
| 2317 | str) | 2703 | str) |
| 2318 | & ")" | -2 ; close list or remove opening | 2704 | & ")" | -2 |
| 2319 | ":" \n | 2705 | ":" \n |
| 2320 | "\"\"\"" - "\"\"\"" \n | 2706 | "\"\"\"" - "\"\"\"" \n |
| 2321 | > _ \n) | 2707 | > _ \n) |
| 2322 | 2708 | ||
| 2323 | (defvar python-default-template "if" | 2709 | (defun python-skeleton-add-menu-items () |
| 2324 | "Default template to expand by `python-expand-template'. | 2710 | "Add menu items to Python->Skeletons menu." |
| 2325 | Updated on each expansion.") | 2711 | (let ((skeletons (sort python-skeleton-available 'string<)) |
| 2712 | (items)) | ||
| 2713 | (dolist (skeleton skeletons) | ||
| 2714 | (easy-menu-add-item | ||
| 2715 | nil '("Python" "Skeletons") | ||
| 2716 | `[,(format | ||
| 2717 | "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-"))) | ||
| 2718 | ,skeleton t])))) | ||
| 2719 | |||
| 2720 | ;;; FFAP | ||
| 2721 | |||
| 2722 | (defcustom python-ffap-setup-code | ||
| 2723 | "def __FFAP_get_module_path(module): | ||
| 2724 | try: | ||
| 2725 | import os | ||
| 2726 | path = __import__(module).__file__ | ||
| 2727 | if path[-4:] == '.pyc' and os.path.exists(path[0:-1]): | ||
| 2728 | path = path[:-1] | ||
| 2729 | return path | ||
| 2730 | except: | ||
| 2731 | return ''" | ||
| 2732 | "Python code to get a module path." | ||
| 2733 | :type 'string | ||
| 2734 | :group 'python) | ||
| 2735 | |||
| 2736 | (defcustom python-ffap-string-code | ||
| 2737 | "__FFAP_get_module_path('''%s''')\n" | ||
| 2738 | "Python code used to get a string with the path of a module." | ||
| 2739 | :type 'string | ||
| 2740 | :group 'python) | ||
| 2741 | |||
| 2742 | (defun python-ffap-module-path (module) | ||
| 2743 | "Function for `ffap-alist' to return path for MODULE." | ||
| 2744 | (let ((process (or | ||
| 2745 | (and (eq major-mode 'inferior-python-mode) | ||
| 2746 | (get-buffer-process (current-buffer))) | ||
| 2747 | (python-shell-get-process)))) | ||
| 2748 | (if (not process) | ||
| 2749 | nil | ||
| 2750 | (let ((module-file | ||
| 2751 | (python-shell-send-string-no-output | ||
| 2752 | (format python-ffap-string-code module) process))) | ||
| 2753 | (when module-file | ||
| 2754 | (substring-no-properties module-file 1 -1)))))) | ||
| 2755 | |||
| 2756 | (eval-after-load "ffap" | ||
| 2757 | '(progn | ||
| 2758 | (push '(python-mode . python-ffap-module-path) ffap-alist) | ||
| 2759 | (push '(inferior-python-mode . python-ffap-module-path) ffap-alist))) | ||
| 2326 | 2760 | ||
| 2327 | (defun python-expand-template (name) | ||
| 2328 | "Expand template named NAME. | ||
| 2329 | Interactively, prompt for the name with completion." | ||
| 2330 | (interactive | ||
| 2331 | (list (completing-read (format "Template to expand (default %s): " | ||
| 2332 | python-default-template) | ||
| 2333 | python-mode-abbrev-table nil t nil nil | ||
| 2334 | python-default-template))) | ||
| 2335 | (if (equal "" name) | ||
| 2336 | (setq name python-default-template) | ||
| 2337 | (setq python-default-template name)) | ||
| 2338 | (let ((sym (abbrev-symbol name python-mode-abbrev-table))) | ||
| 2339 | (if sym | ||
| 2340 | (abbrev-insert sym) | ||
| 2341 | (error "Undefined template: %s" name)))) | ||
| 2342 | 2761 | ||
| 2343 | ;;;; Bicycle Repair Man support | 2762 | ;;; Code check |
| 2344 | 2763 | ||
| 2345 | (autoload 'pymacs-load "pymacs" nil t) | 2764 | (defcustom python-check-command |
| 2346 | (autoload 'brm-init "bikeemacs") | 2765 | "pyflakes" |
| 2347 | (defvar brm-menu) | 2766 | "Command used to check a Python file." |
| 2348 | 2767 | :type 'string | |
| 2349 | ;; I'm not sure how useful BRM really is, and it's certainly dangerous | 2768 | :group 'python) |
| 2350 | ;; the way it modifies files outside Emacs... Also note that the | 2769 | |
| 2351 | ;; current BRM loses with tabs used for indentation -- I submitted a | 2770 | (defcustom python-check-buffer-name |
| 2352 | ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>. | 2771 | "*Python check: %s*" |
| 2353 | (defun python-setup-brm () | 2772 | "Buffer name used for check commands." |
| 2354 | "Set up Bicycle Repair Man refactoring tool (if available). | 2773 | :type 'string |
| 2355 | 2774 | :group 'python) | |
| 2356 | Note that the `refactoring' features change files independently of | 2775 | |
| 2357 | Emacs and may modify and save the contents of the current buffer | 2776 | (defvar python-check-custom-command nil |
| 2358 | without confirmation." | 2777 | "Internal use.") |
| 2359 | (interactive) | 2778 | |
| 2360 | (condition-case data | 2779 | (defun python-check (command) |
| 2361 | (unless (fboundp 'brm-rename) | 2780 | "Check a Python file (default current buffer's file). |
| 2362 | (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe | 2781 | Runs COMMAND, a shell command, as if by `compile'. See |
| 2363 | (let ((py-mode-map (make-sparse-keymap)) ; it assumes this | 2782 | `python-check-command' for the default." |
| 2364 | (features (cons 'python-mode features))) ; and requires this | 2783 | (interactive |
| 2365 | (brm-init) ; second line of normal recipe | 2784 | (list (read-string "Check command: " |
| 2366 | (remove-hook 'python-mode-hook ; undo this from `brm-init' | 2785 | (or python-check-custom-command |
| 2367 | (lambda () (easy-menu-add brm-menu))) | 2786 | (concat python-check-command " " |
| 2368 | (easy-menu-define | 2787 | (shell-quote-argument |
| 2369 | python-brm-menu python-mode-map | 2788 | (or |
| 2370 | "Bicycle Repair Man" | 2789 | (let ((name (buffer-file-name))) |
| 2371 | '("BicycleRepairMan" | 2790 | (and name |
| 2372 | :help "Interface to navigation and refactoring tool" | 2791 | (file-name-nondirectory name))) |
| 2373 | "Queries" | 2792 | ""))))))) |
| 2374 | ["Find References" brm-find-references | 2793 | (setq python-check-custom-command command) |
| 2375 | :help "Find references to name at point in compilation buffer"] | 2794 | (save-some-buffers (not compilation-ask-about-save) nil) |
| 2376 | ["Find Definition" brm-find-definition | 2795 | (let ((process-environment (python-shell-calculate-process-environment)) |
| 2377 | :help "Find definition of name at point"] | 2796 | (exec-path (python-shell-calculate-exec-path))) |
| 2378 | "-" | 2797 | (compilation-start command nil |
| 2379 | "Refactoring" | 2798 | (lambda (mode-name) |
| 2380 | ["Rename" brm-rename | 2799 | (format python-check-buffer-name command))))) |
| 2381 | :help "Replace name at point with a new name everywhere"] | 2800 | |
| 2382 | ["Extract Method" brm-extract-method | ||
| 2383 | :active (and mark-active (not buffer-read-only)) | ||
| 2384 | :help "Replace statements in region with a method"] | ||
| 2385 | ["Extract Local Variable" brm-extract-local-variable | ||
| 2386 | :active (and mark-active (not buffer-read-only)) | ||
| 2387 | :help "Replace expression in region with an assignment"] | ||
| 2388 | ["Inline Local Variable" brm-inline-local-variable | ||
| 2389 | :help | ||
| 2390 | "Substitute uses of variable at point with its definition"] | ||
| 2391 | ;; Fixme: Should check for anything to revert. | ||
| 2392 | ["Undo Last Refactoring" brm-undo :help ""])))) | ||
| 2393 | (error (error "BicycleRepairMan setup failed: %s" data)))) | ||
| 2394 | 2801 | ||
| 2395 | ;;;; Modes. | 2802 | ;;; Eldoc |
| 2803 | |||
| 2804 | (defcustom python-eldoc-setup-code | ||
| 2805 | "def __PYDOC_get_help(obj): | ||
| 2806 | try: | ||
| 2807 | import inspect | ||
| 2808 | if hasattr(obj, 'startswith'): | ||
| 2809 | obj = eval(obj, globals()) | ||
| 2810 | doc = inspect.getdoc(obj) | ||
| 2811 | if not doc and callable(obj): | ||
| 2812 | target = None | ||
| 2813 | if inspect.isclass(obj) and hasattr(obj, '__init__'): | ||
| 2814 | target = obj.__init__ | ||
| 2815 | objtype = 'class' | ||
| 2816 | else: | ||
| 2817 | target = obj | ||
| 2818 | objtype = 'def' | ||
| 2819 | if target: | ||
| 2820 | args = inspect.formatargspec( | ||
| 2821 | *inspect.getargspec(target) | ||
| 2822 | ) | ||
| 2823 | name = obj.__name__ | ||
| 2824 | doc = '{objtype} {name}{args}'.format( | ||
| 2825 | objtype=objtype, name=name, args=args | ||
| 2826 | ) | ||
| 2827 | else: | ||
| 2828 | doc = doc.splitlines()[0] | ||
| 2829 | except: | ||
| 2830 | doc = '' | ||
| 2831 | try: | ||
| 2832 | exec('print doc') | ||
| 2833 | except SyntaxError: | ||
| 2834 | print(doc)" | ||
| 2835 | "Python code to setup documentation retrieval." | ||
| 2836 | :type 'string | ||
| 2837 | :group 'python) | ||
| 2838 | |||
| 2839 | (defcustom python-eldoc-string-code | ||
| 2840 | "__PYDOC_get_help('''%s''')\n" | ||
| 2841 | "Python code used to get a string with the documentation of an object." | ||
| 2842 | :type 'string | ||
| 2843 | :group 'python) | ||
| 2396 | 2844 | ||
| 2397 | ;; pdb tracking is alert once this file is loaded, but takes no action if | 2845 | (defun python-eldoc--get-doc-at-point (&optional force-input force-process) |
| 2398 | ;; `python-pdbtrack-do-tracking-p' is nil. | 2846 | "Internal implementation to get documentation at point. |
| 2399 | (add-hook 'comint-output-filter-functions 'python-pdbtrack-track-stack-file) | 2847 | If not FORCE-INPUT is passed then what |
| 2848 | `python-info-current-symbol' returns will be used. If not | ||
| 2849 | FORCE-PROCESS is passed what `python-shell-get-process' returns | ||
| 2850 | is used." | ||
| 2851 | (let ((process (or force-process (python-shell-get-process)))) | ||
| 2852 | (if (not process) | ||
| 2853 | (error "Eldoc needs an inferior Python process running") | ||
| 2854 | (let ((input (or force-input | ||
| 2855 | (python-info-current-symbol t)))) | ||
| 2856 | (and input | ||
| 2857 | (python-shell-send-string-no-output | ||
| 2858 | (format python-eldoc-string-code input) | ||
| 2859 | process)))))) | ||
| 2400 | 2860 | ||
| 2401 | (defvar outline-heading-end-regexp) | 2861 | (defun python-eldoc-function () |
| 2402 | (defvar eldoc-documentation-function) | 2862 | "`eldoc-documentation-function' for Python. |
| 2403 | (defvar python-mode-running) ;Dynamically scoped var. | 2863 | For this to work the best as possible you should call |
| 2864 | `python-shell-send-buffer' from time to time so context in | ||
| 2865 | inferior python process is updated properly." | ||
| 2866 | (python-eldoc--get-doc-at-point)) | ||
| 2404 | 2867 | ||
| 2868 | (defun python-eldoc-at-point (symbol) | ||
| 2869 | "Get help on SYMBOL using `help'. | ||
| 2870 | Interactively, prompt for symbol." | ||
| 2871 | (interactive | ||
| 2872 | (let ((symbol (python-info-current-symbol t)) | ||
| 2873 | (enable-recursive-minibuffers t)) | ||
| 2874 | (list (read-string (if symbol | ||
| 2875 | (format "Describe symbol (default %s): " symbol) | ||
| 2876 | "Describe symbol: ") | ||
| 2877 | nil nil symbol)))) | ||
| 2878 | (message (python-eldoc--get-doc-at-point symbol))) | ||
| 2879 | |||
| 2880 | (add-to-list 'debug-ignored-errors | ||
| 2881 | "^Eldoc needs an inferior Python process running.") | ||
| 2882 | |||
| 2883 | |||
| 2884 | ;;; Misc helpers | ||
| 2885 | |||
| 2886 | (defun python-info-current-defun (&optional include-type) | ||
| 2887 | "Return name of surrounding function with Python compatible dotty syntax. | ||
| 2888 | Optional argument INCLUDE-TYPE indicates to include the type of the defun. | ||
| 2889 | This function is compatible to be used as | ||
| 2890 | `add-log-current-defun-function' since it returns nil if point is | ||
| 2891 | not inside a defun." | ||
| 2892 | (save-restriction | ||
| 2893 | (widen) | ||
| 2894 | (save-excursion | ||
| 2895 | (end-of-line 1) | ||
| 2896 | (let ((names) | ||
| 2897 | (starting-indentation | ||
| 2898 | (save-excursion | ||
| 2899 | (and | ||
| 2900 | (python-nav-beginning-of-defun 1) | ||
| 2901 | ;; This extra number is just for checking code | ||
| 2902 | ;; against indentation to work well on first run. | ||
| 2903 | (+ (current-indentation) 4)))) | ||
| 2904 | (starting-point (point))) | ||
| 2905 | ;; Check point is inside a defun. | ||
| 2906 | (when (and starting-indentation | ||
| 2907 | (< starting-point | ||
| 2908 | (save-excursion | ||
| 2909 | (python-nav-end-of-defun) | ||
| 2910 | (point)))) | ||
| 2911 | (catch 'exit | ||
| 2912 | (while (python-nav-beginning-of-defun 1) | ||
| 2913 | (when (< (current-indentation) starting-indentation) | ||
| 2914 | (setq starting-indentation (current-indentation)) | ||
| 2915 | (setq names | ||
| 2916 | (cons | ||
| 2917 | (if (not include-type) | ||
| 2918 | (match-string-no-properties 1) | ||
| 2919 | (mapconcat 'identity | ||
| 2920 | (split-string | ||
| 2921 | (match-string-no-properties 0)) " ")) | ||
| 2922 | names))) | ||
| 2923 | (and (= (current-indentation) 0) (throw 'exit t))))) | ||
| 2924 | (and names | ||
| 2925 | (mapconcat (lambda (string) string) names ".")))))) | ||
| 2926 | |||
| 2927 | (defun python-info-current-symbol (&optional replace-self) | ||
| 2928 | "Return current symbol using dotty syntax. | ||
| 2929 | With optional argument REPLACE-SELF convert \"self\" to current | ||
| 2930 | parent defun name." | ||
| 2931 | (let ((name | ||
| 2932 | (and (not (python-syntax-comment-or-string-p)) | ||
| 2933 | (with-syntax-table python-dotty-syntax-table | ||
| 2934 | (let ((sym (symbol-at-point))) | ||
| 2935 | (and sym | ||
| 2936 | (substring-no-properties (symbol-name sym)))))))) | ||
| 2937 | (when name | ||
| 2938 | (if (not replace-self) | ||
| 2939 | name | ||
| 2940 | (let ((current-defun (python-info-current-defun))) | ||
| 2941 | (if (not current-defun) | ||
| 2942 | name | ||
| 2943 | (replace-regexp-in-string | ||
| 2944 | (python-rx line-start word-start "self" word-end ?.) | ||
| 2945 | (concat | ||
| 2946 | (mapconcat 'identity | ||
| 2947 | (butlast (split-string current-defun "\\.")) | ||
| 2948 | ".") ".") | ||
| 2949 | name))))))) | ||
| 2950 | |||
| 2951 | (defun python-info-statement-starts-block-p () | ||
| 2952 | "Return non-nil if current statement opens a block." | ||
| 2953 | (save-excursion | ||
| 2954 | (python-nav-beginning-of-statement) | ||
| 2955 | (looking-at (python-rx block-start)))) | ||
| 2956 | |||
| 2957 | (defun python-info-statement-ends-block-p () | ||
| 2958 | "Return non-nil if point is at end of block." | ||
| 2959 | (let ((end-of-block-pos (save-excursion | ||
| 2960 | (python-nav-end-of-block))) | ||
| 2961 | (end-of-statement-pos (save-excursion | ||
| 2962 | (python-nav-end-of-statement)))) | ||
| 2963 | (and end-of-block-pos end-of-statement-pos | ||
| 2964 | (= end-of-block-pos end-of-statement-pos)))) | ||
| 2965 | |||
| 2966 | (defun python-info-beginning-of-statement-p () | ||
| 2967 | "Return non-nil if point is at beginning of statement." | ||
| 2968 | (= (point) (save-excursion | ||
| 2969 | (python-nav-beginning-of-statement) | ||
| 2970 | (point)))) | ||
| 2971 | |||
| 2972 | (defun python-info-end-of-statement-p () | ||
| 2973 | "Return non-nil if point is at end of statement." | ||
| 2974 | (= (point) (save-excursion | ||
| 2975 | (python-nav-end-of-statement) | ||
| 2976 | (point)))) | ||
| 2977 | |||
| 2978 | (defun python-info-beginning-of-block-p () | ||
| 2979 | "Return non-nil if point is at beginning of block." | ||
| 2980 | (and (python-info-beginning-of-statement-p) | ||
| 2981 | (python-info-statement-starts-block-p))) | ||
| 2982 | |||
| 2983 | (defun python-info-end-of-block-p () | ||
| 2984 | "Return non-nil if point is at end of block." | ||
| 2985 | (and (python-info-end-of-statement-p) | ||
| 2986 | (python-info-statement-ends-block-p))) | ||
| 2987 | |||
| 2988 | (defun python-info-closing-block () | ||
| 2989 | "Return the point of the block the current line closes." | ||
| 2990 | (let ((closing-word (save-excursion | ||
| 2991 | (back-to-indentation) | ||
| 2992 | (current-word))) | ||
| 2993 | (indentation (current-indentation))) | ||
| 2994 | (when (member closing-word python-indent-dedenters) | ||
| 2995 | (save-excursion | ||
| 2996 | (forward-line -1) | ||
| 2997 | (while (and (> (current-indentation) indentation) | ||
| 2998 | (not (bobp)) | ||
| 2999 | (not (back-to-indentation)) | ||
| 3000 | (forward-line -1))) | ||
| 3001 | (back-to-indentation) | ||
| 3002 | (cond | ||
| 3003 | ((not (equal indentation (current-indentation))) nil) | ||
| 3004 | ((string= closing-word "elif") | ||
| 3005 | (when (member (current-word) '("if" "elif")) | ||
| 3006 | (point-marker))) | ||
| 3007 | ((string= closing-word "else") | ||
| 3008 | (when (member (current-word) '("if" "elif" "except" "for" "while")) | ||
| 3009 | (point-marker))) | ||
| 3010 | ((string= closing-word "except") | ||
| 3011 | (when (member (current-word) '("try")) | ||
| 3012 | (point-marker))) | ||
| 3013 | ((string= closing-word "finally") | ||
| 3014 | (when (member (current-word) '("except" "else")) | ||
| 3015 | (point-marker)))))))) | ||
| 3016 | |||
| 3017 | (defun python-info-closing-block-message (&optional closing-block-point) | ||
| 3018 | "Message the contents of the block the current line closes. | ||
| 3019 | With optional argument CLOSING-BLOCK-POINT use that instead of | ||
| 3020 | recalculating it calling `python-info-closing-block'." | ||
| 3021 | (let ((point (or closing-block-point (python-info-closing-block)))) | ||
| 3022 | (when point | ||
| 3023 | (save-restriction | ||
| 3024 | (widen) | ||
| 3025 | (message "Closes %s" (save-excursion | ||
| 3026 | (goto-char point) | ||
| 3027 | (back-to-indentation) | ||
| 3028 | (buffer-substring | ||
| 3029 | (point) (line-end-position)))))))) | ||
| 3030 | |||
| 3031 | (defun python-info-line-ends-backslash-p (&optional line-number) | ||
| 3032 | "Return non-nil if current line ends with backslash. | ||
| 3033 | With optional argument LINE-NUMBER, check that line instead." | ||
| 3034 | (save-excursion | ||
| 3035 | (save-restriction | ||
| 3036 | (widen) | ||
| 3037 | (when line-number | ||
| 3038 | (goto-char line-number)) | ||
| 3039 | (while (and (not (eobp)) | ||
| 3040 | (goto-char (line-end-position)) | ||
| 3041 | (python-syntax-context 'paren) | ||
| 3042 | (not (equal (char-before (point)) ?\\))) | ||
| 3043 | (forward-line 1)) | ||
| 3044 | (when (equal (char-before) ?\\) | ||
| 3045 | (point-marker))))) | ||
| 3046 | |||
| 3047 | (defun python-info-beginning-of-backslash (&optional line-number) | ||
| 3048 | "Return the point where the backslashed line start. | ||
| 3049 | Optional argument LINE-NUMBER forces the line number to check against." | ||
| 3050 | (save-excursion | ||
| 3051 | (save-restriction | ||
| 3052 | (widen) | ||
| 3053 | (when line-number | ||
| 3054 | (goto-char line-number)) | ||
| 3055 | (when (python-info-line-ends-backslash-p) | ||
| 3056 | (while (save-excursion | ||
| 3057 | (goto-char (line-beginning-position)) | ||
| 3058 | (python-syntax-context 'paren)) | ||
| 3059 | (forward-line -1)) | ||
| 3060 | (back-to-indentation) | ||
| 3061 | (point-marker))))) | ||
| 3062 | |||
| 3063 | (defun python-info-continuation-line-p () | ||
| 3064 | "Check if current line is continuation of another. | ||
| 3065 | When current line is continuation of another return the point | ||
| 3066 | where the continued line ends." | ||
| 3067 | (save-excursion | ||
| 3068 | (save-restriction | ||
| 3069 | (widen) | ||
| 3070 | (let* ((context-type (progn | ||
| 3071 | (back-to-indentation) | ||
| 3072 | (python-syntax-context-type))) | ||
| 3073 | (line-start (line-number-at-pos)) | ||
| 3074 | (context-start (when context-type | ||
| 3075 | (python-syntax-context context-type)))) | ||
| 3076 | (cond ((equal context-type 'paren) | ||
| 3077 | ;; Lines inside a paren are always a continuation line | ||
| 3078 | ;; (except the first one). | ||
| 3079 | (python-util-forward-comment -1) | ||
| 3080 | (point-marker)) | ||
| 3081 | ((member context-type '(string comment)) | ||
| 3082 | ;; move forward an roll again | ||
| 3083 | (goto-char context-start) | ||
| 3084 | (python-util-forward-comment) | ||
| 3085 | (python-info-continuation-line-p)) | ||
| 3086 | (t | ||
| 3087 | ;; Not within a paren, string or comment, the only way | ||
| 3088 | ;; we are dealing with a continuation line is that | ||
| 3089 | ;; previous line contains a backslash, and this can | ||
| 3090 | ;; only be the previous line from current | ||
| 3091 | (back-to-indentation) | ||
| 3092 | (python-util-forward-comment -1) | ||
| 3093 | (when (and (equal (1- line-start) (line-number-at-pos)) | ||
| 3094 | (python-info-line-ends-backslash-p)) | ||
| 3095 | (point-marker)))))))) | ||
| 3096 | |||
| 3097 | (defun python-info-block-continuation-line-p () | ||
| 3098 | "Return non-nil if current line is a continuation of a block." | ||
| 3099 | (save-excursion | ||
| 3100 | (when (python-info-continuation-line-p) | ||
| 3101 | (forward-line -1) | ||
| 3102 | (back-to-indentation) | ||
| 3103 | (when (looking-at (python-rx block-start)) | ||
| 3104 | (point-marker))))) | ||
| 3105 | |||
| 3106 | (defun python-info-assignment-continuation-line-p () | ||
| 3107 | "Check if current line is a continuation of an assignment. | ||
| 3108 | When current line is continuation of another with an assignment | ||
| 3109 | return the point of the first non-blank character after the | ||
| 3110 | operator." | ||
| 3111 | (save-excursion | ||
| 3112 | (when (python-info-continuation-line-p) | ||
| 3113 | (forward-line -1) | ||
| 3114 | (back-to-indentation) | ||
| 3115 | (when (and (not (looking-at (python-rx block-start))) | ||
| 3116 | (and (re-search-forward (python-rx not-simple-operator | ||
| 3117 | assignment-operator | ||
| 3118 | not-simple-operator) | ||
| 3119 | (line-end-position) t) | ||
| 3120 | (not (python-syntax-context-type)))) | ||
| 3121 | (skip-syntax-forward "\s") | ||
| 3122 | (point-marker))))) | ||
| 3123 | |||
| 3124 | (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss) | ||
| 3125 | "Check if point is at `beginning-of-defun' using SYNTAX-PPSS." | ||
| 3126 | (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss)))) | ||
| 3127 | (save-excursion | ||
| 3128 | (beginning-of-line 1) | ||
| 3129 | (looking-at python-nav-beginning-of-defun-regexp)))) | ||
| 3130 | |||
| 3131 | (defun python-info-current-line-comment-p () | ||
| 3132 | "Check if current line is a comment line." | ||
| 3133 | (char-equal (or (char-after (+ (point) (current-indentation))) ?_) ?#)) | ||
| 3134 | |||
| 3135 | (defun python-info-current-line-empty-p () | ||
| 3136 | "Check if current line is empty, ignoring whitespace." | ||
| 3137 | (save-excursion | ||
| 3138 | (beginning-of-line 1) | ||
| 3139 | (looking-at | ||
| 3140 | (python-rx line-start (* whitespace) | ||
| 3141 | (group (* not-newline)) | ||
| 3142 | (* whitespace) line-end)) | ||
| 3143 | (string-equal "" (match-string-no-properties 1)))) | ||
| 3144 | |||
| 3145 | |||
| 3146 | ;;; Utility functions | ||
| 3147 | |||
| 3148 | (defun python-util-position (item seq) | ||
| 3149 | "Find the first occurrence of ITEM in SEQ. | ||
| 3150 | Return the index of the matching item, or nil if not found." | ||
| 3151 | (let ((member-result (member item seq))) | ||
| 3152 | (when member-result | ||
| 3153 | (- (length seq) (length member-result))))) | ||
| 3154 | |||
| 3155 | ;; Stolen from org-mode | ||
| 3156 | (defun python-util-clone-local-variables (from-buffer &optional regexp) | ||
| 3157 | "Clone local variables from FROM-BUFFER. | ||
| 3158 | Optional argument REGEXP selects variables to clone and defaults | ||
| 3159 | to \"^python-\"." | ||
| 3160 | (mapc | ||
| 3161 | (lambda (pair) | ||
| 3162 | (and (symbolp (car pair)) | ||
| 3163 | (string-match (or regexp "^python-") | ||
| 3164 | (symbol-name (car pair))) | ||
| 3165 | (set (make-local-variable (car pair)) | ||
| 3166 | (cdr pair)))) | ||
| 3167 | (buffer-local-variables from-buffer))) | ||
| 3168 | |||
| 3169 | (defun python-util-forward-comment (&optional direction) | ||
| 3170 | "Python mode specific version of `forward-comment'. | ||
| 3171 | Optional argument DIRECTION defines the direction to move to." | ||
| 3172 | (let ((comment-start (python-syntax-context 'comment)) | ||
| 3173 | (factor (if (< (or direction 0) 0) | ||
| 3174 | -99999 | ||
| 3175 | 99999))) | ||
| 3176 | (when comment-start | ||
| 3177 | (goto-char comment-start)) | ||
| 3178 | (forward-comment factor))) | ||
| 3179 | |||
| 3180 | |||
| 2405 | ;;;###autoload | 3181 | ;;;###autoload |
| 2406 | (define-derived-mode python-mode prog-mode "Python" | 3182 | (define-derived-mode python-mode prog-mode "Python" |
| 2407 | "Major mode for editing Python files. | 3183 | "Major mode for editing Python files. |
| 2408 | Turns on Font Lock mode unconditionally since it is currently required | 3184 | |
| 2409 | for correct parsing of the source. | 3185 | \\{python-mode-map} |
| 2410 | See also `jython-mode', which is actually invoked if the buffer appears to | 3186 | Entry to this mode calls the value of `python-mode-hook' |
| 2411 | contain Jython code. See also `run-python' and associated Python mode | 3187 | if that value is non-nil." |
| 2412 | commands for running Python under Emacs. | 3188 | (set (make-local-variable 'tab-width) 8) |
| 2413 | 3189 | (set (make-local-variable 'indent-tabs-mode) nil) | |
| 2414 | The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal | 3190 | |
| 2415 | with nested `def' and `class' blocks. They take the innermost one as | 3191 | (set (make-local-variable 'comment-start) "# ") |
| 2416 | current without distinguishing method and class definitions. Used multiple | 3192 | (set (make-local-variable 'comment-start-skip) "#+\\s-*") |
| 2417 | times, they move over others at the same indentation level until they reach | 3193 | |
| 2418 | the end of definitions at that level, when they move up a level. | 3194 | (set (make-local-variable 'parse-sexp-lookup-properties) t) |
| 2419 | \\<python-mode-map> | 3195 | (set (make-local-variable 'parse-sexp-ignore-comments) t) |
| 2420 | Colon is electric: it outdents the line if appropriate, e.g. for | 3196 | |
| 2421 | an else statement. \\[python-backspace] at the beginning of an indented statement | 3197 | (set (make-local-variable 'forward-sexp-function) |
| 2422 | deletes a level of indentation to close the current block; otherwise it | 3198 | 'python-nav-forward-sexp) |
| 2423 | deletes a character backward. TAB indents the current line relative to | 3199 | |
| 2424 | the preceding code. Successive TABs, with no intervening command, cycle | ||
| 2425 | through the possibilities for indentation on the basis of enclosing blocks. | ||
| 2426 | |||
| 2427 | \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no | ||
| 2428 | effect outside them. | ||
| 2429 | |||
| 2430 | Supports Eldoc mode (only for functions, using a Python process), | ||
| 2431 | Info-Look and Imenu. In Outline minor mode, `class' and `def' | ||
| 2432 | lines count as headers. Symbol completion is available in the | ||
| 2433 | same way as in the Python shell using the `rlcompleter' module | ||
| 2434 | and this is added to the Hippie Expand functions locally if | ||
| 2435 | Hippie Expand mode is turned on. Completion of symbols of the | ||
| 2436 | form x.y only works if the components are literal | ||
| 2437 | module/attribute names, not variables. An abbrev table is set up | ||
| 2438 | with skeleton expansions for compound statement templates. | ||
| 2439 | |||
| 2440 | \\{python-mode-map}" | ||
| 2441 | :group 'python | ||
| 2442 | (set (make-local-variable 'font-lock-defaults) | 3200 | (set (make-local-variable 'font-lock-defaults) |
| 2443 | '(python-font-lock-keywords nil nil nil nil | 3201 | '(python-font-lock-keywords nil nil nil nil)) |
| 2444 | ;; This probably isn't worth it. | 3202 | |
| 2445 | ;; (font-lock-syntactic-face-function | ||
| 2446 | ;; . python-font-lock-syntactic-face-function) | ||
| 2447 | )) | ||
| 2448 | (set (make-local-variable 'syntax-propertize-function) | 3203 | (set (make-local-variable 'syntax-propertize-function) |
| 2449 | python-syntax-propertize-function) | 3204 | python-syntax-propertize-function) |
| 2450 | (set (make-local-variable 'parse-sexp-lookup-properties) t) | 3205 | |
| 2451 | (set (make-local-variable 'parse-sexp-ignore-comments) t) | 3206 | (set (make-local-variable 'indent-line-function) |
| 2452 | (set (make-local-variable 'comment-start) "# ") | 3207 | #'python-indent-line-function) |
| 2453 | (set (make-local-variable 'indent-line-function) #'python-indent-line) | ||
| 2454 | (set (make-local-variable 'indent-region-function) #'python-indent-region) | 3208 | (set (make-local-variable 'indent-region-function) #'python-indent-region) |
| 3209 | |||
| 2455 | (set (make-local-variable 'paragraph-start) "\\s-*$") | 3210 | (set (make-local-variable 'paragraph-start) "\\s-*$") |
| 2456 | (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph) | 3211 | (set (make-local-variable 'fill-paragraph-function) |
| 2457 | (set (make-local-variable 'require-final-newline) mode-require-final-newline) | 3212 | 'python-fill-paragraph) |
| 2458 | (set (make-local-variable 'add-log-current-defun-function) | 3213 | |
| 2459 | #'python-current-defun) | ||
| 2460 | (set (make-local-variable 'outline-regexp) | ||
| 2461 | (rx (* space) (or "class" "def" "elif" "else" "except" "finally" | ||
| 2462 | "for" "if" "try" "while" "with") | ||
| 2463 | symbol-end)) | ||
| 2464 | (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n") | ||
| 2465 | (set (make-local-variable 'outline-level) #'python-outline-level) | ||
| 2466 | (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil) | ||
| 2467 | (set (make-local-variable 'beginning-of-defun-function) | 3214 | (set (make-local-variable 'beginning-of-defun-function) |
| 2468 | 'python-beginning-of-defun) | 3215 | #'python-nav-beginning-of-defun) |
| 2469 | (set (make-local-variable 'end-of-defun-function) 'python-end-of-defun) | 3216 | (set (make-local-variable 'end-of-defun-function) |
| 2470 | (add-hook 'which-func-functions 'python-which-func nil t) | 3217 | #'python-nav-end-of-defun) |
| 2471 | (setq imenu-create-index-function #'python-imenu-create-index) | 3218 | |
| 3219 | (add-hook 'completion-at-point-functions | ||
| 3220 | 'python-completion-complete-at-point nil 'local) | ||
| 3221 | |||
| 3222 | (add-hook 'post-self-insert-hook | ||
| 3223 | 'python-indent-post-self-insert-function nil 'local) | ||
| 3224 | |||
| 3225 | (set (make-local-variable 'imenu-extract-index-name-function) | ||
| 3226 | #'python-info-current-defun) | ||
| 3227 | |||
| 3228 | (set (make-local-variable 'add-log-current-defun-function) | ||
| 3229 | #'python-info-current-defun) | ||
| 3230 | |||
| 3231 | (add-hook 'which-func-functions #'python-info-current-defun nil t) | ||
| 3232 | |||
| 3233 | (set (make-local-variable 'skeleton-further-elements) | ||
| 3234 | '((abbrev-mode nil) | ||
| 3235 | (< '(backward-delete-char-untabify (min python-indent-offset | ||
| 3236 | (current-column)))) | ||
| 3237 | (^ '(- (1+ (current-indentation)))))) | ||
| 3238 | |||
| 2472 | (set (make-local-variable 'eldoc-documentation-function) | 3239 | (set (make-local-variable 'eldoc-documentation-function) |
| 2473 | #'python-eldoc-function) | 3240 | #'python-eldoc-function) |
| 2474 | (add-hook 'eldoc-mode-hook | 3241 | |
| 2475 | (lambda () (run-python nil t)) ; need it running | ||
| 2476 | nil t) | ||
| 2477 | (add-hook 'completion-at-point-functions | ||
| 2478 | 'python-completion-at-point nil 'local) | ||
| 2479 | ;; Fixme: should be in hideshow. This seems to be of limited use | ||
| 2480 | ;; since it isn't (can't be) indentation-based. Also hide-level | ||
| 2481 | ;; doesn't seem to work properly. | ||
| 2482 | (add-to-list 'hs-special-modes-alist | 3242 | (add-to-list 'hs-special-modes-alist |
| 2483 | `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#" | 3243 | `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#" |
| 2484 | ,(lambda (_arg) | 3244 | ,(lambda (arg) |
| 2485 | (python-end-of-defun) | 3245 | (python-nav-end-of-defun)) nil)) |
| 2486 | (skip-chars-backward " \t\n")) | ||
| 2487 | nil)) | ||
| 2488 | (set (make-local-variable 'skeleton-further-elements) | ||
| 2489 | '((< '(backward-delete-char-untabify (min python-indent | ||
| 2490 | (current-column)))) | ||
| 2491 | (^ '(- (1+ (current-indentation)))))) | ||
| 2492 | ;; Python defines TABs as being 8-char wide. | ||
| 2493 | (set (make-local-variable 'tab-width) 8) | ||
| 2494 | (when python-guess-indent (python-guess-indent)) | ||
| 2495 | ;; Let's make it harder for the user to shoot himself in the foot. | ||
| 2496 | (unless (= tab-width python-indent) | ||
| 2497 | (setq indent-tabs-mode nil)) | ||
| 2498 | (set (make-local-variable 'python-command) python-python-command) | ||
| 2499 | (python-find-imports) | ||
| 2500 | (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode | ||
| 2501 | (let ((python-mode-running t)) | ||
| 2502 | (python-maybe-jython)))) | ||
| 2503 | |||
| 2504 | ;; Not done automatically in Emacs 21 or 22. | ||
| 2505 | (defcustom python-mode-hook nil | ||
| 2506 | "Hook run when entering Python mode." | ||
| 2507 | :group 'python | ||
| 2508 | :type 'hook) | ||
| 2509 | (custom-add-option 'python-mode-hook 'imenu-add-menubar-index) | ||
| 2510 | (custom-add-option 'python-mode-hook | ||
| 2511 | (lambda () | ||
| 2512 | "Turn off Indent Tabs mode." | ||
| 2513 | (setq indent-tabs-mode nil))) | ||
| 2514 | (custom-add-option 'python-mode-hook 'turn-on-eldoc-mode) | ||
| 2515 | (custom-add-option 'python-mode-hook 'abbrev-mode) | ||
| 2516 | (custom-add-option 'python-mode-hook 'python-setup-brm) | ||
| 2517 | 3246 | ||
| 2518 | ;;;###autoload | 3247 | (set (make-local-variable 'mode-require-final-newline) t) |
| 2519 | (define-derived-mode jython-mode python-mode "Jython" | ||
| 2520 | "Major mode for editing Jython files. | ||
| 2521 | Like `python-mode', but sets up parameters for Jython subprocesses. | ||
| 2522 | Runs `jython-mode-hook' after `python-mode-hook'." | ||
| 2523 | :group 'python | ||
| 2524 | (set (make-local-variable 'python-command) python-jython-command)) | ||
| 2525 | 3248 | ||
| 2526 | 3249 | (set (make-local-variable 'outline-regexp) | |
| 3250 | (python-rx (* space) block-start)) | ||
| 3251 | (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n") | ||
| 3252 | (set (make-local-variable 'outline-level) | ||
| 3253 | #'(lambda () | ||
| 3254 | "`outline-level' function for Python mode." | ||
| 3255 | (1+ (/ (current-indentation) python-indent-offset)))) | ||
| 2527 | 3256 | ||
| 2528 | ;; pdbtrack features | 3257 | (python-skeleton-add-menu-items) |
| 2529 | |||
| 2530 | (defun python-pdbtrack-overlay-arrow (activation) | ||
| 2531 | "Activate or deactivate arrow at beginning-of-line in current buffer." | ||
| 2532 | (if activation | ||
| 2533 | (progn | ||
| 2534 | (setq overlay-arrow-position (make-marker) | ||
| 2535 | overlay-arrow-string "=>" | ||
| 2536 | python-pdbtrack-is-tracking-p t) | ||
| 2537 | (set-marker overlay-arrow-position | ||
| 2538 | (line-beginning-position) | ||
| 2539 | (current-buffer))) | ||
| 2540 | (setq overlay-arrow-position nil | ||
| 2541 | python-pdbtrack-is-tracking-p nil))) | ||
| 2542 | |||
| 2543 | (defun python-pdbtrack-track-stack-file (_text) | ||
| 2544 | "Show the file indicated by the pdb stack entry line, in a separate window. | ||
| 2545 | |||
| 2546 | Activity is disabled if the buffer-local variable | ||
| 2547 | `python-pdbtrack-do-tracking-p' is nil. | ||
| 2548 | |||
| 2549 | We depend on the pdb input prompt being a match for | ||
| 2550 | `python-pdbtrack-input-prompt'. | ||
| 2551 | |||
| 2552 | If the traceback target file path is invalid, we look for the | ||
| 2553 | most recently visited python-mode buffer which either has the | ||
| 2554 | name of the current function or class, or which defines the | ||
| 2555 | function or class. This is to provide for scripts not in the | ||
| 2556 | local file system (e.g., Zope's 'Script \(Python)', but it's not | ||
| 2557 | Zope specific). If you put a copy of the script in a buffer | ||
| 2558 | named for the script and activate python-mode, then pdbtrack will | ||
| 2559 | find it." | ||
| 2560 | ;; Instead of trying to piece things together from partial text | ||
| 2561 | ;; (which can be almost useless depending on Emacs version), we | ||
| 2562 | ;; monitor to the point where we have the next pdb prompt, and then | ||
| 2563 | ;; check all text from comint-last-input-end to process-mark. | ||
| 2564 | ;; | ||
| 2565 | ;; Also, we're very conservative about clearing the overlay arrow, | ||
| 2566 | ;; to minimize residue. This means, for instance, that executing | ||
| 2567 | ;; other pdb commands wipe out the highlight. You can always do a | ||
| 2568 | ;; 'where' (aka 'w') PDB command to reveal the overlay arrow. | ||
| 2569 | |||
| 2570 | (let* ((origbuf (current-buffer)) | ||
| 2571 | (currproc (get-buffer-process origbuf))) | ||
| 2572 | |||
| 2573 | (if (not (and currproc python-pdbtrack-do-tracking-p)) | ||
| 2574 | (python-pdbtrack-overlay-arrow nil) | ||
| 2575 | |||
| 2576 | (let* ((procmark (process-mark currproc)) | ||
| 2577 | (block (buffer-substring (max comint-last-input-end | ||
| 2578 | (- procmark | ||
| 2579 | python-pdbtrack-track-range)) | ||
| 2580 | procmark)) | ||
| 2581 | target target_fname target_lineno target_buffer) | ||
| 2582 | |||
| 2583 | (if (not (string-match (concat python-pdbtrack-input-prompt "$") block)) | ||
| 2584 | (python-pdbtrack-overlay-arrow nil) | ||
| 2585 | |||
| 2586 | (setq block (ansi-color-filter-apply block)) | ||
| 2587 | (setq target (python-pdbtrack-get-source-buffer block)) | ||
| 2588 | |||
| 2589 | (if (stringp target) | ||
| 2590 | (progn | ||
| 2591 | (python-pdbtrack-overlay-arrow nil) | ||
| 2592 | (message "pdbtrack: %s" target)) | ||
| 2593 | |||
| 2594 | (setq target_lineno (car target) | ||
| 2595 | target_buffer (cadr target) | ||
| 2596 | target_fname (buffer-file-name target_buffer)) | ||
| 2597 | (switch-to-buffer-other-window target_buffer) | ||
| 2598 | (goto-char (point-min)) | ||
| 2599 | (forward-line (1- target_lineno)) | ||
| 2600 | (message "pdbtrack: line %s, file %s" target_lineno target_fname) | ||
| 2601 | (python-pdbtrack-overlay-arrow t) | ||
| 2602 | (pop-to-buffer origbuf t) | ||
| 2603 | ;; in large shell buffers, above stuff may cause point to lag output | ||
| 2604 | (goto-char procmark) | ||
| 2605 | ))))) | ||
| 2606 | ) | ||
| 2607 | |||
| 2608 | (defun python-pdbtrack-get-source-buffer (block) | ||
| 2609 | "Return line number and buffer of code indicated by block's traceback text. | ||
| 2610 | |||
| 2611 | We look first to visit the file indicated in the trace. | ||
| 2612 | |||
| 2613 | Failing that, we look for the most recently visited python-mode buffer | ||
| 2614 | with the same name or having the named function. | ||
| 2615 | |||
| 2616 | If we're unable find the source code we return a string describing the | ||
| 2617 | problem." | ||
| 2618 | |||
| 2619 | (if (not (string-match python-pdbtrack-stack-entry-regexp block)) | ||
| 2620 | |||
| 2621 | "Traceback cue not found" | ||
| 2622 | |||
| 2623 | (let* ((filename (match-string 1 block)) | ||
| 2624 | (lineno (string-to-number (match-string 2 block))) | ||
| 2625 | (funcname (match-string 3 block)) | ||
| 2626 | funcbuffer) | ||
| 2627 | |||
| 2628 | (cond ((file-exists-p filename) | ||
| 2629 | (list lineno (find-file-noselect filename))) | ||
| 2630 | |||
| 2631 | ((setq funcbuffer (python-pdbtrack-grub-for-buffer funcname lineno)) | ||
| 2632 | (if (string-match "/Script (Python)$" filename) | ||
| 2633 | ;; Add in number of lines for leading '##' comments: | ||
| 2634 | (setq lineno | ||
| 2635 | (+ lineno | ||
| 2636 | (with-current-buffer funcbuffer | ||
| 2637 | (if (equal (point-min)(point-max)) | ||
| 2638 | 0 | ||
| 2639 | (count-lines | ||
| 2640 | (point-min) | ||
| 2641 | (max (point-min) | ||
| 2642 | (string-match "^\\([^#]\\|#[^#]\\|#$\\)" | ||
| 2643 | (buffer-substring | ||
| 2644 | (point-min) (point-max))) | ||
| 2645 | ))))))) | ||
| 2646 | (list lineno funcbuffer)) | ||
| 2647 | |||
| 2648 | ((= (elt filename 0) ?\<) | ||
| 2649 | (format "(Non-file source: '%s')" filename)) | ||
| 2650 | |||
| 2651 | (t (format "Not found: %s(), %s" funcname filename))) | ||
| 2652 | ) | ||
| 2653 | ) | ||
| 2654 | ) | ||
| 2655 | |||
| 2656 | (defun python-pdbtrack-grub-for-buffer (funcname _lineno) | ||
| 2657 | "Find recent Python mode buffer named, or having function named FUNCNAME." | ||
| 2658 | (let ((buffers (buffer-list)) | ||
| 2659 | buf | ||
| 2660 | got) | ||
| 2661 | (while (and buffers (not got)) | ||
| 2662 | (setq buf (car buffers) | ||
| 2663 | buffers (cdr buffers)) | ||
| 2664 | (if (and (with-current-buffer buf | ||
| 2665 | (string= major-mode "python-mode")) | ||
| 2666 | (or (string-match funcname (buffer-name buf)) | ||
| 2667 | (string-match (concat "^\\s-*\\(def\\|class\\)\\s-+" | ||
| 2668 | funcname "\\s-*(") | ||
| 2669 | (with-current-buffer buf | ||
| 2670 | (buffer-substring (point-min) | ||
| 2671 | (point-max)))))) | ||
| 2672 | (setq got buf))) | ||
| 2673 | got)) | ||
| 2674 | |||
| 2675 | ;; Python subprocess utilities and filters | ||
| 2676 | (defun python-execute-file (proc filename) | ||
| 2677 | "Send to Python interpreter process PROC \"execfile('FILENAME')\". | ||
| 2678 | Make that process's buffer visible and force display. Also make | ||
| 2679 | comint believe the user typed this string so that | ||
| 2680 | `kill-output-from-shell' does The Right Thing." | ||
| 2681 | (let ((curbuf (current-buffer)) | ||
| 2682 | (procbuf (process-buffer proc)) | ||
| 2683 | ; (comint-scroll-to-bottom-on-output t) | ||
| 2684 | (msg (format "## working on region in file %s...\n" filename)) | ||
| 2685 | ;; add some comment, so that we can filter it out of history | ||
| 2686 | (cmd (format "execfile(r'%s') # PYTHON-MODE\n" filename))) | ||
| 2687 | (unwind-protect | ||
| 2688 | (with-current-buffer procbuf | ||
| 2689 | (goto-char (point-max)) | ||
| 2690 | (move-marker (process-mark proc) (point)) | ||
| 2691 | (funcall (process-filter proc) proc msg)) | ||
| 2692 | (set-buffer curbuf)) | ||
| 2693 | (process-send-string proc cmd))) | ||
| 2694 | |||
| 2695 | (defun python-pdbtrack-toggle-stack-tracking (arg) | ||
| 2696 | (interactive "P") | ||
| 2697 | (if (not (get-buffer-process (current-buffer))) | ||
| 2698 | (error "No process associated with buffer '%s'" (current-buffer))) | ||
| 2699 | ;; missing or 0 is toggle, >0 turn on, <0 turn off | ||
| 2700 | (if (or (not arg) | ||
| 2701 | (zerop (setq arg (prefix-numeric-value arg)))) | ||
| 2702 | (setq python-pdbtrack-do-tracking-p (not python-pdbtrack-do-tracking-p)) | ||
| 2703 | (setq python-pdbtrack-do-tracking-p (> arg 0))) | ||
| 2704 | (message "%sabled Python's pdbtrack" | ||
| 2705 | (if python-pdbtrack-do-tracking-p "En" "Dis"))) | ||
| 2706 | |||
| 2707 | (defun turn-on-pdbtrack () | ||
| 2708 | (interactive) | ||
| 2709 | (python-pdbtrack-toggle-stack-tracking 1)) | ||
| 2710 | 3258 | ||
| 2711 | (defun turn-off-pdbtrack () | 3259 | (make-local-variable 'python-shell-internal-buffer) |
| 2712 | (interactive) | ||
| 2713 | (python-pdbtrack-toggle-stack-tracking 0)) | ||
| 2714 | 3260 | ||
| 2715 | (defun python-sentinel (_proc _msg) | 3261 | (when python-indent-guess-indent-offset |
| 2716 | (setq overlay-arrow-position nil)) | 3262 | (python-indent-guess-indent-offset))) |
| 2717 | 3263 | ||
| 2718 | (defun python-unload-function () | ||
| 2719 | "Unload the Python library." | ||
| 2720 | (remove-hook 'comint-output-filter-functions 'python-pdbtrack-track-stack-file) | ||
| 2721 | (setq minor-mode-alist (assq-delete-all 'python-pdbtrack-is-tracking-p | ||
| 2722 | minor-mode-alist)) | ||
| 2723 | (dolist (error '("^No symbol" "^Can't shift all lines enough")) | ||
| 2724 | (setq debug-ignored-errors (delete error debug-ignored-errors))) | ||
| 2725 | ;; continue standard unloading | ||
| 2726 | nil) | ||
| 2727 | 3264 | ||
| 2728 | (provide 'python) | 3265 | (provide 'python) |
| 2729 | (provide 'python-21) | 3266 | |
| 3267 | ;; Local Variables: | ||
| 3268 | ;; coding: utf-8 | ||
| 3269 | ;; indent-tabs-mode: nil | ||
| 3270 | ;; End: | ||
| 2730 | 3271 | ||
| 2731 | ;;; python.el ends here | 3272 | ;;; python.el ends here |