| 1 | ;;; python.el --- Python's flying circus support for Emacs |
| 2 | |
| 3 | ;; Copyright (C) 2010, 2011 Free Software Foundation, Inc. |
| 4 | |
| 5 | ;; Author: Fabián E. Gallina <fabian@anue.biz> |
| 6 | ;; URL: https://github.com/fgallina/python.el |
| 7 | ;; Version: 0.23.1 |
| 8 | ;; Maintainer: FSF |
| 9 | ;; Created: Jul 2010 |
| 10 | ;; Keywords: languages |
| 11 | |
| 12 | ;; This file is NOT part of GNU Emacs. |
| 13 | |
| 14 | ;; python.el is free software: you can redistribute it and/or modify |
| 15 | ;; it under the terms of the GNU General Public License as published by |
| 16 | ;; the Free Software Foundation, either version 3 of the License, or |
| 17 | ;; (at your option) any later version. |
| 18 | |
| 19 | ;; python.el is distributed in the hope that it will be useful, |
| 20 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 21 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 22 | ;; GNU General Public License for more details. |
| 23 | |
| 24 | ;; You should have received a copy of the GNU General Public License |
| 25 | ;; along with python.el. If not, see <http://www.gnu.org/licenses/>. |
| 26 | |
| 27 | ;;; Commentary: |
| 28 | |
| 29 | ;; Major mode for editing Python files with some fontification and |
| 30 | ;; indentation bits extracted from original Dave Love's python.el |
| 31 | ;; found in GNU/Emacs. |
| 32 | |
| 33 | ;; While it probably has less features than Dave Love's python.el and |
| 34 | ;; PSF's python-mode.el it provides the main stuff you'll need while |
| 35 | ;; keeping it simple :) |
| 36 | |
| 37 | ;; Implements Syntax highlighting, Indentation, Movement, Shell |
| 38 | ;; interaction, Shell completion, Shell virtualenv support, Pdb |
| 39 | ;; tracking, Symbol completion, Skeletons, FFAP, Code Check, Eldoc, |
| 40 | ;; imenu. |
| 41 | |
| 42 | ;; Syntax highlighting: Fontification of code is provided and supports |
| 43 | ;; python's triple quoted strings properly. |
| 44 | |
| 45 | ;; Indentation: Automatic indentation with indentation cycling is |
| 46 | ;; provided, it allows you to navigate different available levels of |
| 47 | ;; indentation by hitting <tab> several times. Also when inserting a |
| 48 | ;; colon the `python-indent-electric-colon' command is invoked and |
| 49 | ;; causes the current line to be dedented automatically if needed. |
| 50 | |
| 51 | ;; Movement: `beginning-of-defun' and `end-of-defun' functions are |
| 52 | ;; properly implemented. There are also specialized |
| 53 | ;; `forward-sentence' and `backward-sentence' replacements |
| 54 | ;; (`python-nav-forward-sentence', `python-nav-backward-sentence' |
| 55 | ;; respectively). Extra functions `python-nav-sentence-start' and |
| 56 | ;; `python-nav-sentence-end' are included to move to the beginning and |
| 57 | ;; to the end of a setence while taking care of multiline definitions. |
| 58 | ;; `python-nav-jump-to-defun' is provided and allows jumping to a |
| 59 | ;; function or class definition quickly in the current buffer. |
| 60 | |
| 61 | ;; Shell interaction: is provided and allows you to execute easily any |
| 62 | ;; block of code of your current buffer in an inferior Python process. |
| 63 | |
| 64 | ;; Shell completion: hitting tab will try to complete the current |
| 65 | ;; word. Shell completion is implemented in a manner that if you |
| 66 | ;; change the `python-shell-interpreter' to any other (for example |
| 67 | ;; IPython) it should be easy to integrate another way to calculate |
| 68 | ;; completions. You just need to specify your custom |
| 69 | ;; `python-shell-completion-setup-code' and |
| 70 | ;; `python-shell-completion-string-code'. |
| 71 | |
| 72 | ;; Here is a complete example of the settings you would use for |
| 73 | ;; iPython 0.11: |
| 74 | |
| 75 | ;; (setq |
| 76 | ;; python-shell-interpreter "ipython" |
| 77 | ;; python-shell-interpreter-args "" |
| 78 | ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: " |
| 79 | ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: " |
| 80 | ;; python-shell-completion-setup-code |
| 81 | ;; "from IPython.core.completerlib import module_completion" |
| 82 | ;; python-shell-completion-module-string-code |
| 83 | ;; "';'.join(module_completion('''%s'''))\n" |
| 84 | ;; python-shell-completion-string-code |
| 85 | ;; "';'.join(get_ipython().Completer.all_completions('''%s'''))\n") |
| 86 | |
| 87 | ;; For iPython 0.10 everything would be the same except for |
| 88 | ;; `python-shell-completion-string-code' and |
| 89 | ;; `python-shell-completion-module-string-code': |
| 90 | |
| 91 | ;; (setq python-shell-completion-string-code |
| 92 | ;; "';'.join(__IP.complete('''%s'''))\n" |
| 93 | ;; python-shell-completion-module-string-code "") |
| 94 | |
| 95 | ;; Unfortunately running iPython on Windows needs some more tweaking. |
| 96 | ;; The way you must set `python-shell-interpreter' and |
| 97 | ;; `python-shell-interpreter-args' is as follows: |
| 98 | |
| 99 | ;; (setq |
| 100 | ;; python-shell-interpreter "C:\\Python27\\python.exe" |
| 101 | ;; python-shell-interpreter-args |
| 102 | ;; "-i C:\\Python27\\Scripts\\ipython-script.py") |
| 103 | |
| 104 | ;; That will spawn the iPython process correctly (Of course you need |
| 105 | ;; to modify the paths according to your system). |
| 106 | |
| 107 | ;; Please note that the default completion system depends on the |
| 108 | ;; readline module, so if you are using some Operating System that |
| 109 | ;; bundles Python without it (like Windows) just install the |
| 110 | ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and |
| 111 | ;; you should be good to go. |
| 112 | |
| 113 | ;; Shell virtualenv support: The shell also contains support for |
| 114 | ;; virtualenvs and other special environment modifications thanks to |
| 115 | ;; `python-shell-process-environment' and `python-shell-exec-path'. |
| 116 | ;; These two variables allows you to modify execution paths and |
| 117 | ;; environment variables to make easy for you to setup virtualenv rules |
| 118 | ;; or behavior modifications when running shells. Here is an example |
| 119 | ;; of how to make shell processes to be run using the /path/to/env/ |
| 120 | ;; virtualenv: |
| 121 | |
| 122 | ;; (setq python-shell-process-environment |
| 123 | ;; (list |
| 124 | ;; (format "PATH=%s" (mapconcat |
| 125 | ;; 'identity |
| 126 | ;; (reverse |
| 127 | ;; (cons (getenv "PATH") |
| 128 | ;; '("/path/to/env/bin/"))) |
| 129 | ;; ":")) |
| 130 | ;; "VIRTUAL_ENV=/path/to/env/")) |
| 131 | ;; (python-shell-exec-path . ("/path/to/env/bin/")) |
| 132 | |
| 133 | ;; Since the above is cumbersome and can be programatically |
| 134 | ;; calculated, the variable `python-shell-virtualenv-path' is |
| 135 | ;; provided. When this variable is set with the path of the |
| 136 | ;; virtualenv to use, `process-environment' and `exec-path' get proper |
| 137 | ;; values in order to run shells inside the specified virtualenv. So |
| 138 | ;; the following will achieve the same as the previous example: |
| 139 | |
| 140 | ;; (setq python-shell-virtualenv-path "/path/to/env/") |
| 141 | |
| 142 | ;; Also the `python-shell-extra-pythonpaths' variable have been |
| 143 | ;; introduced as simple way of adding paths to the PYTHONPATH without |
| 144 | ;; affecting existing values. |
| 145 | |
| 146 | ;; Pdb tracking: when you execute a block of code that contains some |
| 147 | ;; call to pdb (or ipdb) it will prompt the block of code and will |
| 148 | ;; follow the execution of pdb marking the current line with an arrow. |
| 149 | |
| 150 | ;; Symbol completion: you can complete the symbol at point. It uses |
| 151 | ;; the shell completion in background so you should run |
| 152 | ;; `python-shell-send-buffer' from time to time to get better results. |
| 153 | |
| 154 | ;; Skeletons: 6 skeletons are provided for simple inserting of class, |
| 155 | ;; def, for, if, try and while. These skeletons are integrated with |
| 156 | ;; dabbrev. If you have `dabbrev-mode' activated and |
| 157 | ;; `python-skeleton-autoinsert' is set to t, then whenever you type |
| 158 | ;; the name of any of those defined and hit SPC, they will be |
| 159 | ;; automatically expanded. |
| 160 | |
| 161 | ;; FFAP: You can find the filename for a given module when using ffap |
| 162 | ;; out of the box. This feature needs an inferior python shell |
| 163 | ;; running. |
| 164 | |
| 165 | ;; Code check: Check the current file for errors with `python-check' |
| 166 | ;; using the program defined in `python-check-command'. |
| 167 | |
| 168 | ;; Eldoc: returns documentation for object at point by using the |
| 169 | ;; inferior python subprocess to inspect its documentation. As you |
| 170 | ;; might guessed you should run `python-shell-send-buffer' from time |
| 171 | ;; to time to get better results too. |
| 172 | |
| 173 | ;; imenu: This mode supports imenu. It builds a plain or tree menu |
| 174 | ;; depending on the value of `python-imenu-make-tree'. Also you can |
| 175 | ;; customize if menu items should include its type using |
| 176 | ;; `python-imenu-include-defun-type'. |
| 177 | |
| 178 | ;; If you used python-mode.el you probably will miss auto-indentation |
| 179 | ;; when inserting newlines. To achieve the same behavior you have |
| 180 | ;; two options: |
| 181 | |
| 182 | ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j. |
| 183 | |
| 184 | ;; 2) Add the following hook in your .emacs: |
| 185 | |
| 186 | ;; (add-hook 'python-mode-hook |
| 187 | ;; #'(lambda () |
| 188 | ;; (define-key python-mode-map "\C-m" 'newline-and-indent))) |
| 189 | |
| 190 | ;; I'd recommend the first one since you'll get the same behavior for |
| 191 | ;; all modes out-of-the-box. |
| 192 | |
| 193 | ;;; Installation: |
| 194 | |
| 195 | ;; Add this to your .emacs: |
| 196 | |
| 197 | ;; (add-to-list 'load-path "/folder/containing/file") |
| 198 | ;; (require 'python) |
| 199 | |
| 200 | ;;; TODO: |
| 201 | |
| 202 | ;;; Code: |
| 203 | |
| 204 | (require 'ansi-color) |
| 205 | (require 'comint) |
| 206 | |
| 207 | (eval-when-compile |
| 208 | (require 'cl) |
| 209 | ;; Avoid compiler warnings |
| 210 | (defvar view-return-to-alist) |
| 211 | (defvar compilation-error-regexp-alist) |
| 212 | (defvar outline-heading-end-regexp)) |
| 213 | |
| 214 | (autoload 'comint-mode "comint") |
| 215 | |
| 216 | ;;;###autoload |
| 217 | (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode)) |
| 218 | ;;;###autoload |
| 219 | (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode)) |
| 220 | |
| 221 | (defgroup python nil |
| 222 | "Python Language's flying circus support for Emacs." |
| 223 | :group 'languages |
| 224 | :version "23.2" |
| 225 | :link '(emacs-commentary-link "python")) |
| 226 | |
| 227 | \f |
| 228 | ;;; Bindings |
| 229 | |
| 230 | (defvar python-mode-map |
| 231 | (let ((map (make-sparse-keymap))) |
| 232 | ;; Movement |
| 233 | (substitute-key-definition 'backward-sentence |
| 234 | 'python-nav-backward-sentence |
| 235 | map global-map) |
| 236 | (substitute-key-definition 'forward-sentence |
| 237 | 'python-nav-forward-sentence |
| 238 | map global-map) |
| 239 | (define-key map "\C-c\C-j" 'python-nav-jump-to-defun) |
| 240 | ;; Indent specific |
| 241 | (define-key map "\177" 'python-indent-dedent-line-backspace) |
| 242 | (define-key map (kbd "<backtab>") 'python-indent-dedent-line) |
| 243 | (define-key map "\C-c<" 'python-indent-shift-left) |
| 244 | (define-key map "\C-c>" 'python-indent-shift-right) |
| 245 | (define-key map ":" 'python-indent-electric-colon) |
| 246 | ;; Skeletons |
| 247 | (define-key map "\C-c\C-tc" 'python-skeleton-class) |
| 248 | (define-key map "\C-c\C-td" 'python-skeleton-def) |
| 249 | (define-key map "\C-c\C-tf" 'python-skeleton-for) |
| 250 | (define-key map "\C-c\C-ti" 'python-skeleton-if) |
| 251 | (define-key map "\C-c\C-tt" 'python-skeleton-try) |
| 252 | (define-key map "\C-c\C-tw" 'python-skeleton-while) |
| 253 | ;; Shell interaction |
| 254 | (define-key map "\C-c\C-s" 'python-shell-send-string) |
| 255 | (define-key map "\C-c\C-r" 'python-shell-send-region) |
| 256 | (define-key map "\C-\M-x" 'python-shell-send-defun) |
| 257 | (define-key map "\C-c\C-c" 'python-shell-send-buffer) |
| 258 | (define-key map "\C-c\C-l" 'python-shell-send-file) |
| 259 | (define-key map "\C-c\C-z" 'python-shell-switch-to-shell) |
| 260 | ;; Some util commands |
| 261 | (define-key map "\C-c\C-v" 'python-check) |
| 262 | (define-key map "\C-c\C-f" 'python-eldoc-at-point) |
| 263 | ;; Utilities |
| 264 | (substitute-key-definition 'complete-symbol 'completion-at-point |
| 265 | map global-map) |
| 266 | (easy-menu-define python-menu map "Python Mode menu" |
| 267 | `("Python" |
| 268 | :help "Python-specific Features" |
| 269 | ["Shift region left" python-indent-shift-left :active mark-active |
| 270 | :help "Shift region left by a single indentation step"] |
| 271 | ["Shift region right" python-indent-shift-right :active mark-active |
| 272 | :help "Shift region right by a single indentation step"] |
| 273 | "-" |
| 274 | ["Start of def/class" beginning-of-defun |
| 275 | :help "Go to start of outermost definition around point"] |
| 276 | ["End of def/class" end-of-defun |
| 277 | :help "Go to end of definition around point"] |
| 278 | ["Mark def/class" mark-defun |
| 279 | :help "Mark outermost definition around point"] |
| 280 | ["Jump to def/class" python-nav-jump-to-defun |
| 281 | :help "Jump to a class or function definition"] |
| 282 | "--" |
| 283 | ("Skeletons") |
| 284 | "---" |
| 285 | ["Start interpreter" run-python |
| 286 | :help "Run inferior Python process in a separate buffer"] |
| 287 | ["Switch to shell" python-shell-switch-to-shell |
| 288 | :help "Switch to running inferior Python process"] |
| 289 | ["Eval string" python-shell-send-string |
| 290 | :help "Eval string in inferior Python session"] |
| 291 | ["Eval buffer" python-shell-send-buffer |
| 292 | :help "Eval buffer in inferior Python session"] |
| 293 | ["Eval region" python-shell-send-region |
| 294 | :help "Eval region in inferior Python session"] |
| 295 | ["Eval defun" python-shell-send-defun |
| 296 | :help "Eval defun in inferior Python session"] |
| 297 | ["Eval file" python-shell-send-file |
| 298 | :help "Eval file in inferior Python session"] |
| 299 | ["Debugger" pdb :help "Run pdb under GUD"] |
| 300 | "----" |
| 301 | ["Check file" python-check |
| 302 | :help "Check file for errors"] |
| 303 | ["Help on symbol" python-eldoc-at-point |
| 304 | :help "Get help on symbol at point"] |
| 305 | ["Complete symbol" completion-at-point |
| 306 | :help "Complete symbol before point"])) |
| 307 | map) |
| 308 | "Keymap for `python-mode'.") |
| 309 | |
| 310 | \f |
| 311 | ;;; Python specialized rx |
| 312 | |
| 313 | (eval-when-compile |
| 314 | (defconst python-rx-constituents |
| 315 | (list |
| 316 | `(block-start . ,(rx symbol-start |
| 317 | (or "def" "class" "if" "elif" "else" "try" |
| 318 | "except" "finally" "for" "while" "with") |
| 319 | symbol-end)) |
| 320 | `(decorator . ,(rx line-start (* space) ?@ (any letter ?_) |
| 321 | (* (any word ?_)))) |
| 322 | `(defun . ,(rx symbol-start (or "def" "class") symbol-end)) |
| 323 | `(symbol-name . ,(rx (any letter ?_) (* (any word ?_)))) |
| 324 | `(open-paren . ,(rx (or "{" "[" "("))) |
| 325 | `(close-paren . ,(rx (or "}" "]" ")"))) |
| 326 | `(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))) |
| 327 | `(not-simple-operator . ,(rx |
| 328 | (not |
| 329 | (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))) |
| 330 | `(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">" |
| 331 | "=" "%" "**" "//" "<<" ">>" "<=" "!=" |
| 332 | "==" ">=" "is" "not"))) |
| 333 | `(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**=" |
| 334 | ">>=" "<<=" "&=" "^=" "|=")))) |
| 335 | "Additional Python specific sexps for `python-rx'")) |
| 336 | |
| 337 | (defmacro python-rx (&rest regexps) |
| 338 | "Python mode specialized rx macro. |
| 339 | This variant of `rx' supports common python named REGEXPS." |
| 340 | (let ((rx-constituents (append python-rx-constituents rx-constituents))) |
| 341 | (cond ((null regexps) |
| 342 | (error "No regexp")) |
| 343 | ((cdr regexps) |
| 344 | (rx-to-string `(and ,@regexps) t)) |
| 345 | (t |
| 346 | (rx-to-string (car regexps) t))))) |
| 347 | |
| 348 | \f |
| 349 | ;;; Font-lock and syntax |
| 350 | (defvar python-font-lock-keywords |
| 351 | ;; Keywords |
| 352 | `(,(rx symbol-start |
| 353 | (or |
| 354 | "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with" |
| 355 | "assert" "else" "if" "pass" "yield" "break" "except" "import" "class" |
| 356 | "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda" |
| 357 | "try" |
| 358 | ;; Python 2: |
| 359 | "print" "exec" |
| 360 | ;; Python 3: |
| 361 | ;; False, None, and True are listed as keywords on the Python 3 |
| 362 | ;; documentation, but since they also qualify as constants they are |
| 363 | ;; fontified like that in order to keep font-lock consistent between |
| 364 | ;; Python versions. |
| 365 | "nonlocal" |
| 366 | ;; Extra: |
| 367 | "self") |
| 368 | symbol-end) |
| 369 | ;; functions |
| 370 | (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_)))) |
| 371 | (1 font-lock-function-name-face)) |
| 372 | ;; classes |
| 373 | (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_)))) |
| 374 | (1 font-lock-type-face)) |
| 375 | ;; Constants |
| 376 | (,(rx symbol-start |
| 377 | (or |
| 378 | "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__" |
| 379 | ;; copyright, license, credits, quit and exit are added by the site |
| 380 | ;; module and they are not intended to be used in programs |
| 381 | "copyright" "credits" "exit" "license" "quit") |
| 382 | symbol-end) . font-lock-constant-face) |
| 383 | ;; Decorators. |
| 384 | (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_)) |
| 385 | (0+ "." (1+ (or word ?_))))) |
| 386 | (1 font-lock-type-face)) |
| 387 | ;; Builtin Exceptions |
| 388 | (,(rx symbol-start |
| 389 | (or |
| 390 | "ArithmeticError" "AssertionError" "AttributeError" "BaseException" |
| 391 | "DeprecationWarning" "EOFError" "EnvironmentError" "Exception" |
| 392 | "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError" |
| 393 | "ImportError" "ImportWarning" "IndexError" "KeyError" |
| 394 | "KeyboardInterrupt" "LookupError" "MemoryError" "NameError" |
| 395 | "NotImplementedError" "OSError" "OverflowError" |
| 396 | "PendingDeprecationWarning" "ReferenceError" "RuntimeError" |
| 397 | "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning" |
| 398 | "SystemError" "SystemExit" "TypeError" "UnboundLocalError" |
| 399 | "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError" |
| 400 | "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError" |
| 401 | "ValueError" "Warning" "WindowsError" "ZeroDivisionError" |
| 402 | ;; Python 2: |
| 403 | "StandardError" |
| 404 | ;; Python 3: |
| 405 | "BufferError" "BytesWarning" "IndentationError" "ResourceWarning" |
| 406 | "TabError") |
| 407 | symbol-end) . font-lock-type-face) |
| 408 | ;; Builtins |
| 409 | (,(rx symbol-start |
| 410 | (or |
| 411 | "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod" |
| 412 | "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate" |
| 413 | "eval" "filter" "float" "format" "frozenset" "getattr" "globals" |
| 414 | "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance" |
| 415 | "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview" |
| 416 | "min" "next" "object" "oct" "open" "ord" "pow" "print" "property" |
| 417 | "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted" |
| 418 | "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip" |
| 419 | "__import__" |
| 420 | ;; Python 2: |
| 421 | "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce" |
| 422 | "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce" |
| 423 | "intern" |
| 424 | ;; Python 3: |
| 425 | "ascii" "bytearray" "bytes" "exec" |
| 426 | ;; Extra: |
| 427 | "__all__" "__doc__" "__name__" "__package__") |
| 428 | symbol-end) . font-lock-builtin-face) |
| 429 | ;; asignations |
| 430 | ;; support for a = b = c = 5 |
| 431 | (,(lambda (limit) |
| 432 | (let ((re (python-rx (group (+ (any word ?. ?_))) |
| 433 | (? ?\[ (+ (not (any ?\]))) ?\]) (* space) |
| 434 | assignment-operator))) |
| 435 | (when (re-search-forward re limit t) |
| 436 | (while (and (python-info-ppss-context 'paren) |
| 437 | (re-search-forward re limit t))) |
| 438 | (if (and (not (python-info-ppss-context 'paren)) |
| 439 | (not (equal (char-after (point-marker)) ?=))) |
| 440 | t |
| 441 | (set-match-data nil))))) |
| 442 | (1 font-lock-variable-name-face nil nil)) |
| 443 | ;; support for a, b, c = (1, 2, 3) |
| 444 | (,(lambda (limit) |
| 445 | (let ((re (python-rx (group (+ (any word ?. ?_))) (* space) |
| 446 | (* ?, (* space) (+ (any word ?. ?_)) (* space)) |
| 447 | ?, (* space) (+ (any word ?. ?_)) (* space) |
| 448 | assignment-operator))) |
| 449 | (when (and (re-search-forward re limit t) |
| 450 | (goto-char (nth 3 (match-data)))) |
| 451 | (while (and (python-info-ppss-context 'paren) |
| 452 | (re-search-forward re limit t)) |
| 453 | (goto-char (nth 3 (match-data)))) |
| 454 | (if (not (python-info-ppss-context 'paren)) |
| 455 | t |
| 456 | (set-match-data nil))))) |
| 457 | (1 font-lock-variable-name-face nil nil)))) |
| 458 | |
| 459 | (defconst python-font-lock-syntactic-keywords |
| 460 | ;; Make outer chars of matching triple-quote sequences into generic |
| 461 | ;; string delimiters. Fixme: Is there a better way? |
| 462 | ;; First avoid a sequence preceded by an odd number of backslashes. |
| 463 | `((,(concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix. |
| 464 | "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)") |
| 465 | (3 (python-quote-syntax))))) |
| 466 | |
| 467 | (defun python-quote-syntax () |
| 468 | "Put `syntax-table' property correctly on triple quote. |
| 469 | Used for syntactic keywords. N is the match number (1, 2 or 3)." |
| 470 | ;; Given a triple quote, we have to check the context to know |
| 471 | ;; whether this is an opening or closing triple or whether it's |
| 472 | ;; quoted anyhow, and should be ignored. (For that we need to do |
| 473 | ;; the same job as `syntax-ppss' to be correct and it seems to be OK |
| 474 | ;; to use it here despite initial worries.) We also have to sort |
| 475 | ;; out a possible prefix -- well, we don't _have_ to, but I think it |
| 476 | ;; should be treated as part of the string. |
| 477 | |
| 478 | ;; Test cases: |
| 479 | ;; ur"""ar""" x='"' # """ |
| 480 | ;; x = ''' """ ' a |
| 481 | ;; ''' |
| 482 | ;; x '"""' x """ \"""" x |
| 483 | (save-excursion |
| 484 | (goto-char (match-beginning 0)) |
| 485 | (let ((syntax (save-match-data (syntax-ppss)))) |
| 486 | (cond |
| 487 | ((eq t (nth 3 syntax)) ; after unclosed fence |
| 488 | ;; Consider property for the last char if in a fenced string. |
| 489 | (goto-char (nth 8 syntax)) ; fence position |
| 490 | (skip-chars-forward "uUrR") ; skip any prefix |
| 491 | ;; Is it a matching sequence? |
| 492 | (if (eq (char-after) (char-after (match-beginning 2))) |
| 493 | (put-text-property (match-beginning 3) (match-end 3) |
| 494 | 'syntax-table (string-to-syntax "|")))) |
| 495 | ((match-end 1) |
| 496 | ;; Consider property for initial char, accounting for prefixes. |
| 497 | (put-text-property (match-beginning 1) (match-end 1) |
| 498 | 'syntax-table (string-to-syntax "|"))) |
| 499 | (t |
| 500 | ;; Consider property for initial char, accounting for prefixes. |
| 501 | (put-text-property (match-beginning 2) (match-end 2) |
| 502 | 'syntax-table (string-to-syntax "|")))) |
| 503 | ))) |
| 504 | |
| 505 | (defvar python-mode-syntax-table |
| 506 | (let ((table (make-syntax-table))) |
| 507 | ;; Give punctuation syntax to ASCII that normally has symbol |
| 508 | ;; syntax or has word syntax and isn't a letter. |
| 509 | (let ((symbol (string-to-syntax "_")) |
| 510 | (sst (standard-syntax-table))) |
| 511 | (dotimes (i 128) |
| 512 | (unless (= i ?_) |
| 513 | (if (equal symbol (aref sst i)) |
| 514 | (modify-syntax-entry i "." table))))) |
| 515 | (modify-syntax-entry ?$ "." table) |
| 516 | (modify-syntax-entry ?% "." table) |
| 517 | ;; exceptions |
| 518 | (modify-syntax-entry ?# "<" table) |
| 519 | (modify-syntax-entry ?\n ">" table) |
| 520 | (modify-syntax-entry ?' "\"" table) |
| 521 | (modify-syntax-entry ?` "$" table) |
| 522 | table) |
| 523 | "Syntax table for Python files.") |
| 524 | |
| 525 | (defvar python-dotty-syntax-table |
| 526 | (let ((table (make-syntax-table python-mode-syntax-table))) |
| 527 | (modify-syntax-entry ?. "w" table) |
| 528 | (modify-syntax-entry ?_ "w" table) |
| 529 | table) |
| 530 | "Dotty syntax table for Python files. |
| 531 | It makes underscores and dots word constituent chars.") |
| 532 | |
| 533 | \f |
| 534 | ;;; Indentation |
| 535 | |
| 536 | (defcustom python-indent-offset 4 |
| 537 | "Default indentation offset for Python." |
| 538 | :group 'python |
| 539 | :type 'integer |
| 540 | :safe 'integerp) |
| 541 | |
| 542 | (defcustom python-indent-guess-indent-offset t |
| 543 | "Non-nil tells Python mode to guess `python-indent-offset' value." |
| 544 | :type 'boolean |
| 545 | :group 'python |
| 546 | :safe 'booleanp) |
| 547 | |
| 548 | (defvar python-indent-current-level 0 |
| 549 | "Current indentation level `python-indent-line-function' is using.") |
| 550 | |
| 551 | (defvar python-indent-levels '(0) |
| 552 | "Levels of indentation available for `python-indent-line-function'.") |
| 553 | |
| 554 | (defvar python-indent-dedenters '("else" "elif" "except" "finally") |
| 555 | "List of words that should be dedented. |
| 556 | These make `python-indent-calculate-indentation' subtract the value of |
| 557 | `python-indent-offset'.") |
| 558 | |
| 559 | (defun python-indent-guess-indent-offset () |
| 560 | "Guess and set `python-indent-offset' for the current buffer." |
| 561 | (save-excursion |
| 562 | (save-restriction |
| 563 | (widen) |
| 564 | (goto-char (point-min)) |
| 565 | (let ((block-end)) |
| 566 | (while (and (not block-end) |
| 567 | (re-search-forward |
| 568 | (python-rx line-start block-start) nil t)) |
| 569 | (when (and |
| 570 | (not (python-info-ppss-context-type)) |
| 571 | (progn |
| 572 | (goto-char (line-end-position)) |
| 573 | (python-util-forward-comment -1) |
| 574 | (if (equal (char-before) ?:) |
| 575 | t |
| 576 | (forward-line 1) |
| 577 | (when (python-info-block-continuation-line-p) |
| 578 | (while (and (python-info-continuation-line-p) |
| 579 | (not (eobp))) |
| 580 | (forward-line 1)) |
| 581 | (python-util-forward-comment -1) |
| 582 | (when (equal (char-before) ?:) |
| 583 | t))))) |
| 584 | (setq block-end (point-marker)))) |
| 585 | (let ((indentation |
| 586 | (when block-end |
| 587 | (goto-char block-end) |
| 588 | (python-util-forward-comment) |
| 589 | (current-indentation)))) |
| 590 | (if indentation |
| 591 | (setq python-indent-offset indentation) |
| 592 | (message "Can't guess python-indent-offset, using defaults: %s" |
| 593 | python-indent-offset))))))) |
| 594 | |
| 595 | (defun python-indent-context () |
| 596 | "Get information on indentation context. |
| 597 | Context information is returned with a cons with the form: |
| 598 | \(STATUS . START) |
| 599 | |
| 600 | Where status can be any of the following symbols: |
| 601 | * inside-paren: If point in between (), {} or [] |
| 602 | * inside-string: If point is inside a string |
| 603 | * after-backslash: Previous line ends in a backslash |
| 604 | * after-beginning-of-block: Point is after beginning of block |
| 605 | * after-line: Point is after normal line |
| 606 | * no-indent: Point is at beginning of buffer or other special case |
| 607 | START is the buffer position where the sexp starts." |
| 608 | (save-restriction |
| 609 | (widen) |
| 610 | (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss))) |
| 611 | (start)) |
| 612 | (cons |
| 613 | (cond |
| 614 | ;; Beginning of buffer |
| 615 | ((save-excursion |
| 616 | (goto-char (line-beginning-position)) |
| 617 | (bobp)) |
| 618 | 'no-indent) |
| 619 | ;; Inside a paren |
| 620 | ((setq start (python-info-ppss-context 'paren ppss)) |
| 621 | 'inside-paren) |
| 622 | ;; Inside string |
| 623 | ((setq start (python-info-ppss-context 'string ppss)) |
| 624 | 'inside-string) |
| 625 | ;; After backslash |
| 626 | ((setq start (when (not (or (python-info-ppss-context 'string ppss) |
| 627 | (python-info-ppss-context 'comment ppss))) |
| 628 | (let ((line-beg-pos (line-beginning-position))) |
| 629 | (when (python-info-line-ends-backslash-p |
| 630 | (1- line-beg-pos)) |
| 631 | (- line-beg-pos 2))))) |
| 632 | 'after-backslash) |
| 633 | ;; After beginning of block |
| 634 | ((setq start (save-excursion |
| 635 | (when (progn |
| 636 | (back-to-indentation) |
| 637 | (python-util-forward-comment -1) |
| 638 | (equal (char-before) ?:)) |
| 639 | ;; Move to the first block start that's not in within |
| 640 | ;; a string, comment or paren and that's not a |
| 641 | ;; continuation line. |
| 642 | (while (and (re-search-backward |
| 643 | (python-rx block-start) nil t) |
| 644 | (or |
| 645 | (python-info-ppss-context 'string) |
| 646 | (python-info-ppss-context 'comment) |
| 647 | (python-info-ppss-context 'paren) |
| 648 | (python-info-continuation-line-p)))) |
| 649 | (when (looking-at (python-rx block-start)) |
| 650 | (point-marker))))) |
| 651 | 'after-beginning-of-block) |
| 652 | ;; After normal line |
| 653 | ((setq start (save-excursion |
| 654 | (back-to-indentation) |
| 655 | (python-util-forward-comment -1) |
| 656 | (python-nav-sentence-start) |
| 657 | (point-marker))) |
| 658 | 'after-line) |
| 659 | ;; Do not indent |
| 660 | (t 'no-indent)) |
| 661 | start)))) |
| 662 | |
| 663 | (defun python-indent-calculate-indentation () |
| 664 | "Calculate correct indentation offset for the current line." |
| 665 | (let* ((indentation-context (python-indent-context)) |
| 666 | (context-status (car indentation-context)) |
| 667 | (context-start (cdr indentation-context))) |
| 668 | (save-restriction |
| 669 | (widen) |
| 670 | (save-excursion |
| 671 | (case context-status |
| 672 | ('no-indent 0) |
| 673 | ;; When point is after beginning of block just add one level |
| 674 | ;; of indentation relative to the context-start |
| 675 | ('after-beginning-of-block |
| 676 | (goto-char context-start) |
| 677 | (+ (current-indentation) python-indent-offset)) |
| 678 | ;; When after a simple line just use previous line |
| 679 | ;; indentation, in the case current line starts with a |
| 680 | ;; `python-indent-dedenters' de-indent one level. |
| 681 | ('after-line |
| 682 | (- |
| 683 | (save-excursion |
| 684 | (goto-char context-start) |
| 685 | (current-indentation)) |
| 686 | (if (progn |
| 687 | (back-to-indentation) |
| 688 | (looking-at (regexp-opt python-indent-dedenters))) |
| 689 | python-indent-offset |
| 690 | 0))) |
| 691 | ;; When inside of a string, do nothing. just use the current |
| 692 | ;; indentation. XXX: perhaps it would be a good idea to |
| 693 | ;; invoke standard text indentation here |
| 694 | ('inside-string |
| 695 | (goto-char context-start) |
| 696 | (current-indentation)) |
| 697 | ;; After backslash we have several posibilities |
| 698 | ('after-backslash |
| 699 | (cond |
| 700 | ;; Check if current line is a dot continuation. For this |
| 701 | ;; the current line must start with a dot and previous |
| 702 | ;; line must contain a dot too. |
| 703 | ((save-excursion |
| 704 | (back-to-indentation) |
| 705 | (when (looking-at "\\.") |
| 706 | ;; If after moving one line back point is inside a paren it |
| 707 | ;; needs to move back until it's not anymore |
| 708 | (while (prog2 |
| 709 | (forward-line -1) |
| 710 | (and (not (bobp)) |
| 711 | (python-info-ppss-context 'paren)))) |
| 712 | (goto-char (line-end-position)) |
| 713 | (while (and (re-search-backward |
| 714 | "\\." (line-beginning-position) t) |
| 715 | (or (python-info-ppss-context 'comment) |
| 716 | (python-info-ppss-context 'string) |
| 717 | (python-info-ppss-context 'paren)))) |
| 718 | (if (and (looking-at "\\.") |
| 719 | (not (or (python-info-ppss-context 'comment) |
| 720 | (python-info-ppss-context 'string) |
| 721 | (python-info-ppss-context 'paren)))) |
| 722 | ;; The indentation is the same column of the |
| 723 | ;; first matching dot that's not inside a |
| 724 | ;; comment, a string or a paren |
| 725 | (current-column) |
| 726 | ;; No dot found on previous line, just add another |
| 727 | ;; indentation level. |
| 728 | (+ (current-indentation) python-indent-offset))))) |
| 729 | ;; Check if prev line is a block continuation |
| 730 | ((let ((block-continuation-start |
| 731 | (python-info-block-continuation-line-p))) |
| 732 | (when block-continuation-start |
| 733 | ;; If block-continuation-start is set jump to that |
| 734 | ;; marker and use first column after the block start |
| 735 | ;; as indentation value. |
| 736 | (goto-char block-continuation-start) |
| 737 | (re-search-forward |
| 738 | (python-rx block-start (* space)) |
| 739 | (line-end-position) t) |
| 740 | (current-column)))) |
| 741 | ;; Check if current line is an assignment continuation |
| 742 | ((let ((assignment-continuation-start |
| 743 | (python-info-assignment-continuation-line-p))) |
| 744 | (when assignment-continuation-start |
| 745 | ;; If assignment-continuation is set jump to that |
| 746 | ;; marker and use first column after the assignment |
| 747 | ;; operator as indentation value. |
| 748 | (goto-char assignment-continuation-start) |
| 749 | (current-column)))) |
| 750 | (t |
| 751 | (forward-line -1) |
| 752 | (goto-char (python-info-beginning-of-backlash)) |
| 753 | (if (save-excursion |
| 754 | (and |
| 755 | (forward-line -1) |
| 756 | (goto-char |
| 757 | (or (python-info-beginning-of-backlash) (point))) |
| 758 | (python-info-line-ends-backslash-p))) |
| 759 | ;; The two previous lines ended in a backslash so we must |
| 760 | ;; respect previous line indentation. |
| 761 | (current-indentation) |
| 762 | ;; What happens here is that we are dealing with the second |
| 763 | ;; line of a backslash continuation, in that case we just going |
| 764 | ;; to add one indentation level. |
| 765 | (+ (current-indentation) python-indent-offset))))) |
| 766 | ;; When inside a paren there's a need to handle nesting |
| 767 | ;; correctly |
| 768 | ('inside-paren |
| 769 | (cond |
| 770 | ;; If current line closes the outtermost open paren use the |
| 771 | ;; current indentation of the context-start line. |
| 772 | ((save-excursion |
| 773 | (skip-syntax-forward "\s" (line-end-position)) |
| 774 | (when (and (looking-at (regexp-opt '(")" "]" "}"))) |
| 775 | (progn |
| 776 | (forward-char 1) |
| 777 | (not (python-info-ppss-context 'paren)))) |
| 778 | (goto-char context-start) |
| 779 | (current-indentation)))) |
| 780 | ;; If open paren is contained on a line by itself add another |
| 781 | ;; indentation level, else look for the first word after the |
| 782 | ;; opening paren and use it's column position as indentation |
| 783 | ;; level. |
| 784 | ((let* ((content-starts-in-newline) |
| 785 | (indent |
| 786 | (save-excursion |
| 787 | (if (setq content-starts-in-newline |
| 788 | (progn |
| 789 | (goto-char context-start) |
| 790 | (forward-char) |
| 791 | (save-restriction |
| 792 | (narrow-to-region |
| 793 | (line-beginning-position) |
| 794 | (line-end-position)) |
| 795 | (python-util-forward-comment)) |
| 796 | (looking-at "$"))) |
| 797 | (+ (current-indentation) python-indent-offset) |
| 798 | (current-column))))) |
| 799 | ;; Adjustments |
| 800 | (cond |
| 801 | ;; If current line closes a nested open paren de-indent one |
| 802 | ;; level. |
| 803 | ((progn |
| 804 | (back-to-indentation) |
| 805 | (looking-at (regexp-opt '(")" "]" "}")))) |
| 806 | (- indent python-indent-offset)) |
| 807 | ;; If the line of the opening paren that wraps the current |
| 808 | ;; line starts a block add another level of indentation to |
| 809 | ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx |
| 810 | ((save-excursion |
| 811 | (when (and content-starts-in-newline |
| 812 | (progn |
| 813 | (goto-char context-start) |
| 814 | (back-to-indentation) |
| 815 | (looking-at (python-rx block-start)))) |
| 816 | (+ indent python-indent-offset)))) |
| 817 | (t indent))))))))))) |
| 818 | |
| 819 | (defun python-indent-calculate-levels () |
| 820 | "Calculate `python-indent-levels' and reset `python-indent-current-level'." |
| 821 | (let* ((indentation (python-indent-calculate-indentation)) |
| 822 | (remainder (% indentation python-indent-offset)) |
| 823 | (steps (/ (- indentation remainder) python-indent-offset))) |
| 824 | (setq python-indent-levels (list 0)) |
| 825 | (dotimes (step steps) |
| 826 | (push (* python-indent-offset (1+ step)) python-indent-levels)) |
| 827 | (when (not (eq 0 remainder)) |
| 828 | (push (+ (* python-indent-offset steps) remainder) python-indent-levels)) |
| 829 | (setq python-indent-levels (nreverse python-indent-levels)) |
| 830 | (setq python-indent-current-level (1- (length python-indent-levels))))) |
| 831 | |
| 832 | (defun python-indent-toggle-levels () |
| 833 | "Toggle `python-indent-current-level' over `python-indent-levels'." |
| 834 | (setq python-indent-current-level (1- python-indent-current-level)) |
| 835 | (when (< python-indent-current-level 0) |
| 836 | (setq python-indent-current-level (1- (length python-indent-levels))))) |
| 837 | |
| 838 | (defun python-indent-line (&optional force-toggle) |
| 839 | "Internal implementation of `python-indent-line-function'. |
| 840 | Uses the offset calculated in |
| 841 | `python-indent-calculate-indentation' and available levels |
| 842 | indicated by the variable `python-indent-levels' to set the |
| 843 | current indentation. |
| 844 | |
| 845 | When the variable `last-command' is equal to |
| 846 | `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles |
| 847 | levels indicated in the variable `python-indent-levels' by |
| 848 | setting the current level in the variable |
| 849 | `python-indent-current-level'. |
| 850 | |
| 851 | When the variable `last-command' is not equal to |
| 852 | `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates |
| 853 | possible indentation levels and saves it in the variable |
| 854 | `python-indent-levels'. Afterwards it sets the variable |
| 855 | `python-indent-current-level' correctly so offset is equal |
| 856 | to (`nth' `python-indent-current-level' `python-indent-levels')" |
| 857 | (if (or (and (eq this-command 'indent-for-tab-command) |
| 858 | (eq last-command this-command)) |
| 859 | force-toggle) |
| 860 | (if (not (equal python-indent-levels '(0))) |
| 861 | (python-indent-toggle-levels) |
| 862 | (python-indent-calculate-levels)) |
| 863 | (python-indent-calculate-levels)) |
| 864 | (beginning-of-line) |
| 865 | (delete-horizontal-space) |
| 866 | (indent-to (nth python-indent-current-level python-indent-levels)) |
| 867 | (save-restriction |
| 868 | (widen) |
| 869 | (let ((closing-block-point (python-info-closing-block))) |
| 870 | (when closing-block-point |
| 871 | (message "Closes %s" (buffer-substring |
| 872 | closing-block-point |
| 873 | (save-excursion |
| 874 | (goto-char closing-block-point) |
| 875 | (line-end-position)))))))) |
| 876 | |
| 877 | (defun python-indent-line-function () |
| 878 | "`indent-line-function' for Python mode. |
| 879 | See `python-indent-line' for details." |
| 880 | (python-indent-line)) |
| 881 | |
| 882 | (defun python-indent-dedent-line () |
| 883 | "De-indent current line." |
| 884 | (interactive "*") |
| 885 | (when (and (not (or (python-info-ppss-context 'string) |
| 886 | (python-info-ppss-context 'comment))) |
| 887 | (<= (point-marker) (save-excursion |
| 888 | (back-to-indentation) |
| 889 | (point-marker))) |
| 890 | (> (current-column) 0)) |
| 891 | (python-indent-line t) |
| 892 | t)) |
| 893 | |
| 894 | (defun python-indent-dedent-line-backspace (arg) |
| 895 | "De-indent current line. |
| 896 | Argument ARG is passed to `backward-delete-char-untabify' when |
| 897 | point is not in between the indentation." |
| 898 | (interactive "*p") |
| 899 | (when (not (python-indent-dedent-line)) |
| 900 | (backward-delete-char-untabify arg))) |
| 901 | (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede) |
| 902 | |
| 903 | (defun python-indent-region (start end) |
| 904 | "Indent a python region automagically. |
| 905 | |
| 906 | Called from a program, START and END specify the region to indent." |
| 907 | (let ((deactivate-mark nil)) |
| 908 | (save-excursion |
| 909 | (goto-char end) |
| 910 | (setq end (point-marker)) |
| 911 | (goto-char start) |
| 912 | (or (bolp) (forward-line 1)) |
| 913 | (while (< (point) end) |
| 914 | (or (and (bolp) (eolp)) |
| 915 | (let (word) |
| 916 | (forward-line -1) |
| 917 | (back-to-indentation) |
| 918 | (setq word (current-word)) |
| 919 | (forward-line 1) |
| 920 | (when word |
| 921 | (beginning-of-line) |
| 922 | (delete-horizontal-space) |
| 923 | (indent-to (python-indent-calculate-indentation))))) |
| 924 | (forward-line 1)) |
| 925 | (move-marker end nil)))) |
| 926 | |
| 927 | (defun python-indent-shift-left (start end &optional count) |
| 928 | "Shift lines contained in region START END by COUNT columns to the left. |
| 929 | COUNT defaults to `python-indent-offset'. If region isn't |
| 930 | active, the current line is shifted. The shifted region includes |
| 931 | the lines in which START and END lie. An error is signaled if |
| 932 | any lines in the region are indented less than COUNT columns." |
| 933 | (interactive |
| 934 | (if mark-active |
| 935 | (list (region-beginning) (region-end) current-prefix-arg) |
| 936 | (list (line-beginning-position) (line-end-position) current-prefix-arg))) |
| 937 | (if count |
| 938 | (setq count (prefix-numeric-value count)) |
| 939 | (setq count python-indent-offset)) |
| 940 | (when (> count 0) |
| 941 | (let ((deactivate-mark nil)) |
| 942 | (save-excursion |
| 943 | (goto-char start) |
| 944 | (while (< (point) end) |
| 945 | (if (and (< (current-indentation) count) |
| 946 | (not (looking-at "[ \t]*$"))) |
| 947 | (error "Can't shift all lines enough")) |
| 948 | (forward-line)) |
| 949 | (indent-rigidly start end (- count)))))) |
| 950 | |
| 951 | (add-to-list 'debug-ignored-errors "^Can't shift all lines enough") |
| 952 | |
| 953 | (defun python-indent-shift-right (start end &optional count) |
| 954 | "Shift lines contained in region START END by COUNT columns to the left. |
| 955 | COUNT defaults to `python-indent-offset'. If region isn't |
| 956 | active, the current line is shifted. The shifted region includes |
| 957 | the lines in which START and END lie." |
| 958 | (interactive |
| 959 | (if mark-active |
| 960 | (list (region-beginning) (region-end) current-prefix-arg) |
| 961 | (list (line-beginning-position) (line-end-position) current-prefix-arg))) |
| 962 | (let ((deactivate-mark nil)) |
| 963 | (if count |
| 964 | (setq count (prefix-numeric-value count)) |
| 965 | (setq count python-indent-offset)) |
| 966 | (indent-rigidly start end count))) |
| 967 | |
| 968 | (defun python-indent-electric-colon (arg) |
| 969 | "Insert a colon and maybe de-indent the current line. |
| 970 | With numeric ARG, just insert that many colons. With |
| 971 | \\[universal-argument], just insert a single colon." |
| 972 | (interactive "*P") |
| 973 | (self-insert-command (if (not (integerp arg)) 1 arg)) |
| 974 | (when (and (not arg) |
| 975 | (eolp) |
| 976 | (not (equal ?: (char-after (- (point-marker) 2)))) |
| 977 | (not (or (python-info-ppss-context 'string) |
| 978 | (python-info-ppss-context 'comment)))) |
| 979 | (let ((indentation (current-indentation)) |
| 980 | (calculated-indentation (python-indent-calculate-indentation))) |
| 981 | (when (> indentation calculated-indentation) |
| 982 | (save-excursion |
| 983 | (indent-line-to calculated-indentation) |
| 984 | (when (not (python-info-closing-block)) |
| 985 | (indent-line-to indentation))))))) |
| 986 | (put 'python-indent-electric-colon 'delete-selection t) |
| 987 | |
| 988 | \f |
| 989 | ;;; Navigation |
| 990 | |
| 991 | (defvar python-nav-beginning-of-defun-regexp |
| 992 | (python-rx line-start (* space) defun (+ space) (group symbol-name)) |
| 993 | "Regexp matching class or function definition. |
| 994 | The name of the defun should be grouped so it can be retrieved |
| 995 | via `match-string'.") |
| 996 | |
| 997 | (defun python-nav-beginning-of-defun (&optional nodecorators) |
| 998 | "Move point to `beginning-of-defun'. |
| 999 | When NODECORATORS is non-nil decorators are not included. This |
| 1000 | is the main part of`python-beginning-of-defun-function' |
| 1001 | implementation. Return non-nil if point is moved to the |
| 1002 | `beginning-of-defun'." |
| 1003 | (let ((indent-pos (save-excursion |
| 1004 | (back-to-indentation) |
| 1005 | (point-marker))) |
| 1006 | (found) |
| 1007 | (include-decorators |
| 1008 | (lambda () |
| 1009 | (when (not nodecorators) |
| 1010 | (when (save-excursion |
| 1011 | (forward-line -1) |
| 1012 | (looking-at (python-rx decorator))) |
| 1013 | (while (and (not (bobp)) |
| 1014 | (forward-line -1) |
| 1015 | (looking-at (python-rx decorator)))) |
| 1016 | (when (not (bobp)) (forward-line 1))))))) |
| 1017 | (if (and (> (point) indent-pos) |
| 1018 | (save-excursion |
| 1019 | (goto-char (line-beginning-position)) |
| 1020 | (looking-at python-nav-beginning-of-defun-regexp))) |
| 1021 | (progn |
| 1022 | (goto-char (line-beginning-position)) |
| 1023 | (funcall include-decorators) |
| 1024 | (setq found t)) |
| 1025 | (goto-char (line-beginning-position)) |
| 1026 | (when (re-search-backward python-nav-beginning-of-defun-regexp nil t) |
| 1027 | (setq found t)) |
| 1028 | (goto-char (or (python-info-ppss-context 'string) (point))) |
| 1029 | (funcall include-decorators)) |
| 1030 | found)) |
| 1031 | |
| 1032 | (defun python-beginning-of-defun-function (&optional arg nodecorators) |
| 1033 | "Move point to the beginning of def or class. |
| 1034 | With positive ARG move that number of functions forward. With |
| 1035 | negative do the same but backwards. When NODECORATORS is non-nil |
| 1036 | decorators are not included. Return non-nil if point is moved to the |
| 1037 | `beginning-of-defun'." |
| 1038 | (when (or (null arg) (= arg 0)) (setq arg 1)) |
| 1039 | (if (> arg 0) |
| 1040 | (dotimes (i arg (python-nav-beginning-of-defun nodecorators))) |
| 1041 | (let ((found)) |
| 1042 | (dotimes (i (- arg) found) |
| 1043 | (python-end-of-defun-function) |
| 1044 | (python-util-forward-comment) |
| 1045 | (goto-char (line-end-position)) |
| 1046 | (when (not (eobp)) |
| 1047 | (setq found |
| 1048 | (python-nav-beginning-of-defun nodecorators))))))) |
| 1049 | |
| 1050 | (defun python-end-of-defun-function () |
| 1051 | "Move point to the end of def or class. |
| 1052 | Returns nil if point is not in a def or class." |
| 1053 | (interactive) |
| 1054 | (let ((beg-defun-indent) |
| 1055 | (decorator-regexp "[[:space:]]*@")) |
| 1056 | (when (looking-at decorator-regexp) |
| 1057 | (while (and (not (eobp)) |
| 1058 | (forward-line 1) |
| 1059 | (looking-at decorator-regexp)))) |
| 1060 | (when (not (looking-at python-nav-beginning-of-defun-regexp)) |
| 1061 | (python-beginning-of-defun-function)) |
| 1062 | (setq beg-defun-indent (current-indentation)) |
| 1063 | (forward-line 1) |
| 1064 | (while (and (forward-line 1) |
| 1065 | (not (eobp)) |
| 1066 | (or (not (current-word)) |
| 1067 | ;; This checks if the indentation is less than the base |
| 1068 | ;; one and if the line is not a comment |
| 1069 | (or (> (current-indentation) beg-defun-indent) |
| 1070 | (equal |
| 1071 | (char-after |
| 1072 | (+ (point) (current-indentation))) ?#))))) |
| 1073 | (python-util-forward-comment) |
| 1074 | (goto-char (line-beginning-position)))) |
| 1075 | |
| 1076 | (defun python-nav-sentence-start () |
| 1077 | "Move to start of current sentence." |
| 1078 | (interactive "^") |
| 1079 | (while (and (not (back-to-indentation)) |
| 1080 | (not (bobp)) |
| 1081 | (when (or |
| 1082 | (save-excursion |
| 1083 | (forward-line -1) |
| 1084 | (python-info-line-ends-backslash-p)) |
| 1085 | (python-info-ppss-context 'string) |
| 1086 | (python-info-ppss-context 'paren)) |
| 1087 | (forward-line -1))))) |
| 1088 | |
| 1089 | (defun python-nav-sentence-end () |
| 1090 | "Move to end of current sentence." |
| 1091 | (interactive "^") |
| 1092 | (while (and (goto-char (line-end-position)) |
| 1093 | (not (eobp)) |
| 1094 | (when (or |
| 1095 | (python-info-line-ends-backslash-p) |
| 1096 | (python-info-ppss-context 'string) |
| 1097 | (python-info-ppss-context 'paren)) |
| 1098 | (forward-line 1))))) |
| 1099 | |
| 1100 | (defun python-nav-backward-sentence (&optional arg) |
| 1101 | "Move backward to start of sentence. With ARG, do it arg times. |
| 1102 | See `python-nav-forward-sentence' for more information." |
| 1103 | (interactive "^p") |
| 1104 | (or arg (setq arg 1)) |
| 1105 | (python-nav-forward-sentence (- arg))) |
| 1106 | |
| 1107 | (defun python-nav-forward-sentence (&optional arg) |
| 1108 | "Move forward to next end of sentence. With ARG, repeat. |
| 1109 | With negative argument, move backward repeatedly to start of sentence." |
| 1110 | (interactive "^p") |
| 1111 | (or arg (setq arg 1)) |
| 1112 | (while (> arg 0) |
| 1113 | (python-util-forward-comment) |
| 1114 | (python-nav-sentence-end) |
| 1115 | (forward-line 1) |
| 1116 | (setq arg (1- arg))) |
| 1117 | (while (< arg 0) |
| 1118 | (python-nav-sentence-end) |
| 1119 | (python-util-forward-comment -1) |
| 1120 | (python-nav-sentence-start) |
| 1121 | (forward-line -1) |
| 1122 | (setq arg (1+ arg)))) |
| 1123 | |
| 1124 | (defun python-nav-list-defun-positions (&optional include-type) |
| 1125 | "Make an Alist of defun names and point markers for current buffer. |
| 1126 | When optional argument INCLUDE-TYPE is non-nil the type is |
| 1127 | included the defun name." |
| 1128 | (let ((defs)) |
| 1129 | (save-restriction |
| 1130 | (widen) |
| 1131 | (save-excursion |
| 1132 | (goto-char (point-max)) |
| 1133 | (while (re-search-backward python-nav-beginning-of-defun-regexp nil t) |
| 1134 | (when (and (not (python-info-ppss-context 'string)) |
| 1135 | (not (python-info-ppss-context 'comment)) |
| 1136 | (not (python-info-ppss-context 'parent))) |
| 1137 | (add-to-list |
| 1138 | 'defs (cons |
| 1139 | (python-info-current-defun include-type) |
| 1140 | (point-marker))))) |
| 1141 | defs)))) |
| 1142 | |
| 1143 | (defun python-nav-read-defun () |
| 1144 | "Read a defun name of current buffer and return its point marker. |
| 1145 | A cons cell with the form (DEFUN-NAME . POINT-MARKER) is returned |
| 1146 | when defun is completed, else nil." |
| 1147 | (let ((defs (python-nav-list-defun-positions))) |
| 1148 | (minibuffer-with-setup-hook |
| 1149 | (lambda () |
| 1150 | (setq minibuffer-completion-table (mapcar 'car defs))) |
| 1151 | (let ((stringdef |
| 1152 | (read-from-minibuffer |
| 1153 | "Jump to definition: " nil |
| 1154 | minibuffer-local-must-match-map))) |
| 1155 | (when (not (string= stringdef "")) |
| 1156 | (assoc-string stringdef defs)))))) |
| 1157 | |
| 1158 | (defun python-nav-jump-to-defun (def) |
| 1159 | "Jump to the definition of DEF in current file." |
| 1160 | (interactive |
| 1161 | (list (python-nav-read-defun))) |
| 1162 | (when (not (called-interactively-p 'interactive)) |
| 1163 | (setq def (assoc-string def (python-nav-list-defun-positions)))) |
| 1164 | (let ((def-marker (cdr def))) |
| 1165 | (when (markerp def-marker) |
| 1166 | (goto-char (marker-position def-marker)) |
| 1167 | (back-to-indentation)))) |
| 1168 | |
| 1169 | \f |
| 1170 | ;;; Shell integration |
| 1171 | |
| 1172 | (defcustom python-shell-buffer-name "Python" |
| 1173 | "Default buffer name for Python interpreter." |
| 1174 | :type 'string |
| 1175 | :group 'python |
| 1176 | :safe 'stringp) |
| 1177 | |
| 1178 | (defcustom python-shell-interpreter "python" |
| 1179 | "Default Python interpreter for shell." |
| 1180 | :type 'string |
| 1181 | :group 'python) |
| 1182 | |
| 1183 | (defcustom python-shell-internal-buffer-name "Python Internal" |
| 1184 | "Default buffer name for the Internal Python interpreter." |
| 1185 | :type 'string |
| 1186 | :group 'python |
| 1187 | :safe 'stringp) |
| 1188 | |
| 1189 | (defcustom python-shell-interpreter-args "-i" |
| 1190 | "Default arguments for the Python interpreter." |
| 1191 | :type 'string |
| 1192 | :group 'python) |
| 1193 | |
| 1194 | (defcustom python-shell-prompt-regexp ">>> " |
| 1195 | "Regular Expression matching top\-level input prompt of python shell. |
| 1196 | It should not contain a caret (^) at the beginning." |
| 1197 | :type 'string |
| 1198 | :group 'python |
| 1199 | :safe 'stringp) |
| 1200 | |
| 1201 | (defcustom python-shell-prompt-block-regexp "[.][.][.] " |
| 1202 | "Regular Expression matching block input prompt of python shell. |
| 1203 | It should not contain a caret (^) at the beginning." |
| 1204 | :type 'string |
| 1205 | :group 'python |
| 1206 | :safe 'stringp) |
| 1207 | |
| 1208 | (defcustom python-shell-prompt-output-regexp "" |
| 1209 | "Regular Expression matching output prompt of python shell. |
| 1210 | It should not contain a caret (^) at the beginning." |
| 1211 | :type 'string |
| 1212 | :group 'python |
| 1213 | :safe 'stringp) |
| 1214 | |
| 1215 | (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ " |
| 1216 | "Regular Expression matching pdb input prompt of python shell. |
| 1217 | It should not contain a caret (^) at the beginning." |
| 1218 | :type 'string |
| 1219 | :group 'python |
| 1220 | :safe 'stringp) |
| 1221 | |
| 1222 | (defcustom python-shell-send-setup-max-wait 5 |
| 1223 | "Seconds to wait for process output before code setup. |
| 1224 | If output is received before the especified time then control is |
| 1225 | returned in that moment and not after waiting." |
| 1226 | :type 'integer |
| 1227 | :group 'python |
| 1228 | :safe 'integerp) |
| 1229 | |
| 1230 | (defcustom python-shell-process-environment nil |
| 1231 | "List of environment variables for Python shell. |
| 1232 | This variable follows the same rules as `process-environment' |
| 1233 | since it merges with it before the process creation routines are |
| 1234 | called. When this variable is nil, the Python shell is run with |
| 1235 | the default `process-environment'." |
| 1236 | :type '(repeat string) |
| 1237 | :group 'python |
| 1238 | :safe 'listp) |
| 1239 | |
| 1240 | (defcustom python-shell-extra-pythonpaths nil |
| 1241 | "List of extra pythonpaths for Python shell. |
| 1242 | The values of this variable are added to the existing value of |
| 1243 | PYTHONPATH in the `process-environment' variable." |
| 1244 | :type '(repeat string) |
| 1245 | :group 'python |
| 1246 | :safe 'listp) |
| 1247 | |
| 1248 | (defcustom python-shell-exec-path nil |
| 1249 | "List of path to search for binaries. |
| 1250 | This variable follows the same rules as `exec-path' since it |
| 1251 | merges with it before the process creation routines are called. |
| 1252 | When this variable is nil, the Python shell is run with the |
| 1253 | default `exec-path'." |
| 1254 | :type '(repeat string) |
| 1255 | :group 'python |
| 1256 | :safe 'listp) |
| 1257 | |
| 1258 | (defcustom python-shell-virtualenv-path nil |
| 1259 | "Path to virtualenv root. |
| 1260 | This variable, when set to a string, makes the values stored in |
| 1261 | `python-shell-process-environment' and `python-shell-exec-path' |
| 1262 | to be modified properly so shells are started with the specified |
| 1263 | virtualenv." |
| 1264 | :type 'string |
| 1265 | :group 'python |
| 1266 | :safe 'stringp) |
| 1267 | |
| 1268 | (defcustom python-shell-setup-codes '(python-shell-completion-setup-code |
| 1269 | python-ffap-setup-code |
| 1270 | python-eldoc-setup-code) |
| 1271 | "List of code run by `python-shell-send-setup-codes'." |
| 1272 | :type '(repeat symbol) |
| 1273 | :group 'python |
| 1274 | :safe 'listp) |
| 1275 | |
| 1276 | (defcustom python-shell-compilation-regexp-alist |
| 1277 | `((,(rx line-start (1+ (any " \t")) "File \"" |
| 1278 | (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c |
| 1279 | "\", line " (group (1+ digit))) |
| 1280 | 1 2) |
| 1281 | (,(rx " in file " (group (1+ not-newline)) " on line " |
| 1282 | (group (1+ digit))) |
| 1283 | 1 2) |
| 1284 | (,(rx line-start "> " (group (1+ (not (any "(\"<")))) |
| 1285 | "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()") |
| 1286 | 1 2)) |
| 1287 | "`compilation-error-regexp-alist' for inferior Python." |
| 1288 | :type '(alist string) |
| 1289 | :group 'python) |
| 1290 | |
| 1291 | (defun python-shell-get-process-name (dedicated) |
| 1292 | "Calculate the appropriate process name for inferior Python process. |
| 1293 | If DEDICATED is t and the variable `buffer-file-name' is non-nil |
| 1294 | returns a string with the form |
| 1295 | `python-shell-buffer-name'[variable `buffer-file-name'] else |
| 1296 | returns the value of `python-shell-buffer-name'. After |
| 1297 | calculating the process name adds the buffer name for the process |
| 1298 | in the `same-window-buffer-names' list." |
| 1299 | (let ((process-name |
| 1300 | (if (and dedicated |
| 1301 | buffer-file-name) |
| 1302 | (format "%s[%s]" python-shell-buffer-name buffer-file-name) |
| 1303 | (format "%s" python-shell-buffer-name)))) |
| 1304 | (add-to-list 'same-window-buffer-names (purecopy |
| 1305 | (format "*%s*" process-name))) |
| 1306 | process-name)) |
| 1307 | |
| 1308 | (defun python-shell-internal-get-process-name () |
| 1309 | "Calculate the appropriate process name for Internal Python process. |
| 1310 | The name is calculated from `python-shell-global-buffer-name' and |
| 1311 | a hash of all relevant global shell settings in order to ensure |
| 1312 | uniqueness for different types of configurations." |
| 1313 | (format "%s [%s]" |
| 1314 | python-shell-internal-buffer-name |
| 1315 | (md5 |
| 1316 | (concat |
| 1317 | (python-shell-parse-command) |
| 1318 | python-shell-prompt-regexp |
| 1319 | python-shell-prompt-block-regexp |
| 1320 | python-shell-prompt-output-regexp |
| 1321 | (mapconcat #'symbol-value python-shell-setup-codes "") |
| 1322 | (mapconcat #'identity python-shell-process-environment "") |
| 1323 | (mapconcat #'identity python-shell-extra-pythonpaths "") |
| 1324 | (mapconcat #'identity python-shell-exec-path "") |
| 1325 | (or python-shell-virtualenv-path "") |
| 1326 | (mapconcat #'identity python-shell-exec-path ""))))) |
| 1327 | |
| 1328 | (defun python-shell-parse-command () |
| 1329 | "Calculate the string used to execute the inferior Python process." |
| 1330 | (format "%s %s" python-shell-interpreter python-shell-interpreter-args)) |
| 1331 | |
| 1332 | (defun python-shell-calculate-process-environment () |
| 1333 | "Calculate process environment given `python-shell-virtualenv-path'." |
| 1334 | (let ((process-environment (append |
| 1335 | python-shell-process-environment |
| 1336 | process-environment nil)) |
| 1337 | (virtualenv (if python-shell-virtualenv-path |
| 1338 | (directory-file-name python-shell-virtualenv-path) |
| 1339 | nil))) |
| 1340 | (when python-shell-extra-pythonpaths |
| 1341 | (setenv "PYTHONPATH" |
| 1342 | (format "%s%s%s" |
| 1343 | (mapconcat 'identity |
| 1344 | python-shell-extra-pythonpaths |
| 1345 | path-separator) |
| 1346 | path-separator |
| 1347 | (or (getenv "PYTHONPATH") "")))) |
| 1348 | (if (not virtualenv) |
| 1349 | process-environment |
| 1350 | (setenv "PYTHONHOME" nil) |
| 1351 | (setenv "PATH" (format "%s/bin%s%s" |
| 1352 | virtualenv path-separator |
| 1353 | (or (getenv "PATH") ""))) |
| 1354 | (setenv "VIRTUAL_ENV" virtualenv)) |
| 1355 | process-environment)) |
| 1356 | |
| 1357 | (defun python-shell-calculate-exec-path () |
| 1358 | "Calculate exec path given `python-shell-virtualenv-path'." |
| 1359 | (let ((path (append python-shell-exec-path |
| 1360 | exec-path nil))) |
| 1361 | (if (not python-shell-virtualenv-path) |
| 1362 | path |
| 1363 | (cons (format "%s/bin" |
| 1364 | (directory-file-name python-shell-virtualenv-path)) |
| 1365 | path)))) |
| 1366 | |
| 1367 | (defun python-comint-output-filter-function (output) |
| 1368 | "Hook run after content is put into comint buffer. |
| 1369 | OUTPUT is a string with the contents of the buffer." |
| 1370 | (ansi-color-filter-apply output)) |
| 1371 | |
| 1372 | (define-derived-mode inferior-python-mode comint-mode "Inferior Python" |
| 1373 | "Major mode for Python inferior process. |
| 1374 | Runs a Python interpreter as a subprocess of Emacs, with Python |
| 1375 | I/O through an Emacs buffer. Variables |
| 1376 | `python-shell-interpreter' and `python-shell-interpreter-args' |
| 1377 | controls which Python interpreter is run. Variables |
| 1378 | `python-shell-prompt-regexp', |
| 1379 | `python-shell-prompt-output-regexp', |
| 1380 | `python-shell-prompt-block-regexp', |
| 1381 | `python-shell-completion-setup-code', |
| 1382 | `python-shell-completion-string-code', |
| 1383 | `python-shell-completion-module-string-code', |
| 1384 | `python-eldoc-setup-code', `python-eldoc-string-code', |
| 1385 | `python-ffap-setup-code' and `python-ffap-string-code' can |
| 1386 | customize this mode for different Python interpreters. |
| 1387 | |
| 1388 | You can also add additional setup code to be run at |
| 1389 | initialization of the interpreter via `python-shell-setup-codes' |
| 1390 | variable. |
| 1391 | |
| 1392 | \(Type \\[describe-mode] in the process buffer for a list of commands.)" |
| 1393 | (set-syntax-table python-mode-syntax-table) |
| 1394 | (setq mode-line-process '(":%s")) |
| 1395 | (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)" |
| 1396 | python-shell-prompt-regexp |
| 1397 | python-shell-prompt-block-regexp |
| 1398 | python-shell-prompt-pdb-regexp)) |
| 1399 | (make-local-variable 'comint-output-filter-functions) |
| 1400 | (add-hook 'comint-output-filter-functions |
| 1401 | 'python-comint-output-filter-function) |
| 1402 | (add-hook 'comint-output-filter-functions |
| 1403 | 'python-pdbtrack-comint-output-filter-function) |
| 1404 | (set (make-local-variable 'compilation-error-regexp-alist) |
| 1405 | python-shell-compilation-regexp-alist) |
| 1406 | (define-key inferior-python-mode-map [remap complete-symbol] |
| 1407 | 'completion-at-point) |
| 1408 | (add-hook 'completion-at-point-functions |
| 1409 | 'python-shell-completion-complete-at-point nil 'local) |
| 1410 | (add-to-list (make-local-variable 'comint-dynamic-complete-functions) |
| 1411 | 'python-shell-completion-complete-at-point) |
| 1412 | (define-key inferior-python-mode-map (kbd "<tab>") |
| 1413 | 'python-shell-completion-complete-or-indent) |
| 1414 | (compilation-shell-minor-mode 1)) |
| 1415 | |
| 1416 | (defun python-shell-make-comint (cmd proc-name &optional pop) |
| 1417 | "Create a python shell comint buffer. |
| 1418 | CMD is the python command to be executed and PROC-NAME is the |
| 1419 | process name the comint buffer will get. After the comint buffer |
| 1420 | is created the `inferior-python-mode' is activated. If POP is |
| 1421 | non-nil the buffer is shown." |
| 1422 | (save-excursion |
| 1423 | (let* ((proc-buffer-name (format "*%s*" proc-name)) |
| 1424 | (process-environment (python-shell-calculate-process-environment)) |
| 1425 | (exec-path (python-shell-calculate-exec-path))) |
| 1426 | (when (not (comint-check-proc proc-buffer-name)) |
| 1427 | (let* ((cmdlist (split-string-and-unquote cmd)) |
| 1428 | (buffer (apply 'make-comint proc-name (car cmdlist) nil |
| 1429 | (cdr cmdlist))) |
| 1430 | (current-buffer (current-buffer))) |
| 1431 | (with-current-buffer buffer |
| 1432 | (inferior-python-mode) |
| 1433 | (python-util-clone-local-variables current-buffer)))) |
| 1434 | (when pop |
| 1435 | (pop-to-buffer proc-buffer-name)) |
| 1436 | proc-buffer-name))) |
| 1437 | |
| 1438 | (defun run-python (dedicated cmd) |
| 1439 | "Run an inferior Python process. |
| 1440 | Input and output via buffer named after |
| 1441 | `python-shell-buffer-name'. If there is a process already |
| 1442 | running in that buffer, just switch to it. |
| 1443 | With argument, allows you to define DEDICATED, so a dedicated |
| 1444 | process for the current buffer is open, and define CMD so you can |
| 1445 | edit the command used to call the interpreter (default is value |
| 1446 | of `python-shell-interpreter' and arguments defined in |
| 1447 | `python-shell-interpreter-args'). Runs the hook |
| 1448 | `inferior-python-mode-hook' (after the `comint-mode-hook' is |
| 1449 | run). |
| 1450 | \(Type \\[describe-mode] in the process buffer for a list of commands.)" |
| 1451 | (interactive |
| 1452 | (if current-prefix-arg |
| 1453 | (list |
| 1454 | (y-or-n-p "Make dedicated process? ") |
| 1455 | (read-string "Run Python: " (python-shell-parse-command))) |
| 1456 | (list nil (python-shell-parse-command)))) |
| 1457 | (python-shell-make-comint cmd (python-shell-get-process-name dedicated) t) |
| 1458 | dedicated) |
| 1459 | |
| 1460 | (defun run-python-internal () |
| 1461 | "Run an inferior Internal Python process. |
| 1462 | Input and output via buffer named after |
| 1463 | `python-shell-internal-buffer-name' and what |
| 1464 | `python-shell-internal-get-process-name' returns. This new kind |
| 1465 | of shell is intended to be used for generic communication related |
| 1466 | to defined configurations. The main difference with global or |
| 1467 | dedicated shells is that these ones are attached to a |
| 1468 | configuration, not a buffer. This means that can be used for |
| 1469 | example to retrieve the sys.path and other stuff, without messing |
| 1470 | with user shells. Runs the hook |
| 1471 | `inferior-python-mode-hook' (after the `comint-mode-hook' is |
| 1472 | run). \(Type \\[describe-mode] in the process buffer for a list |
| 1473 | of commands.)" |
| 1474 | (interactive) |
| 1475 | (set-process-query-on-exit-flag |
| 1476 | (get-buffer-process |
| 1477 | (python-shell-make-comint |
| 1478 | (python-shell-parse-command) |
| 1479 | (python-shell-internal-get-process-name))) nil)) |
| 1480 | |
| 1481 | (defun python-shell-get-process () |
| 1482 | "Get inferior Python process for current buffer and return it." |
| 1483 | (let* ((dedicated-proc-name (python-shell-get-process-name t)) |
| 1484 | (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name)) |
| 1485 | (global-proc-name (python-shell-get-process-name nil)) |
| 1486 | (global-proc-buffer-name (format "*%s*" global-proc-name)) |
| 1487 | (dedicated-running (comint-check-proc dedicated-proc-buffer-name)) |
| 1488 | (global-running (comint-check-proc global-proc-buffer-name))) |
| 1489 | ;; Always prefer dedicated |
| 1490 | (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name) |
| 1491 | (and global-running global-proc-buffer-name))))) |
| 1492 | |
| 1493 | (defun python-shell-get-or-create-process () |
| 1494 | "Get or create an inferior Python process for current buffer and return it." |
| 1495 | (let* ((old-buffer (current-buffer)) |
| 1496 | (dedicated-proc-name (python-shell-get-process-name t)) |
| 1497 | (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name)) |
| 1498 | (global-proc-name (python-shell-get-process-name nil)) |
| 1499 | (global-proc-buffer-name (format "*%s*" global-proc-name)) |
| 1500 | (dedicated-running (comint-check-proc dedicated-proc-buffer-name)) |
| 1501 | (global-running (comint-check-proc global-proc-buffer-name)) |
| 1502 | (current-prefix-arg 4)) |
| 1503 | (when (and (not dedicated-running) (not global-running)) |
| 1504 | (if (call-interactively 'run-python) |
| 1505 | (setq dedicated-running t) |
| 1506 | (setq global-running t))) |
| 1507 | ;; Always prefer dedicated |
| 1508 | (switch-to-buffer old-buffer) |
| 1509 | (get-buffer-process (if dedicated-running |
| 1510 | dedicated-proc-buffer-name |
| 1511 | global-proc-buffer-name)))) |
| 1512 | |
| 1513 | (defvar python-shell-internal-buffer nil |
| 1514 | "Current internal shell buffer for the current buffer. |
| 1515 | This is really not necessary at all for the code to work but it's |
| 1516 | there for compatibility with CEDET.") |
| 1517 | (make-variable-buffer-local 'python-shell-internal-buffer) |
| 1518 | |
| 1519 | (defun python-shell-internal-get-or-create-process () |
| 1520 | "Get or create an inferior Internal Python process." |
| 1521 | (let* ((proc-name (python-shell-internal-get-process-name)) |
| 1522 | (proc-buffer-name (format "*%s*" proc-name))) |
| 1523 | (run-python-internal) |
| 1524 | (setq python-shell-internal-buffer proc-buffer-name) |
| 1525 | (get-buffer-process proc-buffer-name))) |
| 1526 | |
| 1527 | (define-obsolete-function-alias |
| 1528 | 'python-proc 'python-shell-internal-get-or-create-process "23.3") |
| 1529 | |
| 1530 | (define-obsolete-variable-alias |
| 1531 | 'python-buffer 'python-shell-internal-buffer "23.3") |
| 1532 | |
| 1533 | (defun python-shell-send-string (string &optional process msg) |
| 1534 | "Send STRING to inferior Python PROCESS. |
| 1535 | When MSG is non-nil messages the first line of STRING." |
| 1536 | (interactive "sPython command: ") |
| 1537 | (let ((process (or process (python-shell-get-or-create-process))) |
| 1538 | (lines (split-string string "\n" t))) |
| 1539 | (when msg |
| 1540 | (message (format "Sent: %s..." (nth 0 lines)))) |
| 1541 | (if (> (length lines) 1) |
| 1542 | (let* ((temp-file-name (make-temp-file "py")) |
| 1543 | (file-name (or (buffer-file-name) temp-file-name))) |
| 1544 | (with-temp-file temp-file-name |
| 1545 | (insert string) |
| 1546 | (delete-trailing-whitespace)) |
| 1547 | (python-shell-send-file file-name process temp-file-name)) |
| 1548 | (comint-send-string process string) |
| 1549 | (when (or (not (string-match "\n$" string)) |
| 1550 | (string-match "\n[ \t].*\n?$" string)) |
| 1551 | (comint-send-string process "\n"))))) |
| 1552 | |
| 1553 | (defun python-shell-send-string-no-output (string &optional process msg) |
| 1554 | "Send STRING to PROCESS and inhibit output. |
| 1555 | When MSG is non-nil messages the first line of STRING. Return |
| 1556 | the output." |
| 1557 | (let* ((output-buffer) |
| 1558 | (process (or process (python-shell-get-or-create-process))) |
| 1559 | (comint-preoutput-filter-functions |
| 1560 | (append comint-preoutput-filter-functions |
| 1561 | '(ansi-color-filter-apply |
| 1562 | (lambda (string) |
| 1563 | (setq output-buffer (concat output-buffer string)) |
| 1564 | ""))))) |
| 1565 | (python-shell-send-string string process msg) |
| 1566 | (accept-process-output process) |
| 1567 | (replace-regexp-in-string |
| 1568 | (if (> (length python-shell-prompt-output-regexp) 0) |
| 1569 | (format "\n*%s$\\|^%s\\|\n$" |
| 1570 | python-shell-prompt-regexp |
| 1571 | (or python-shell-prompt-output-regexp "")) |
| 1572 | (format "\n*$\\|^%s\\|\n$" |
| 1573 | python-shell-prompt-regexp)) |
| 1574 | "" output-buffer))) |
| 1575 | |
| 1576 | (defun python-shell-internal-send-string (string) |
| 1577 | "Send STRING to the Internal Python interpreter. |
| 1578 | Returns the output. See `python-shell-send-string-no-output'." |
| 1579 | (python-shell-send-string-no-output |
| 1580 | ;; Makes this function compatible with the old |
| 1581 | ;; python-send-receive. (At least for CEDET). |
| 1582 | (replace-regexp-in-string "_emacs_out +" "" string) |
| 1583 | (python-shell-internal-get-or-create-process) nil)) |
| 1584 | |
| 1585 | (define-obsolete-function-alias |
| 1586 | 'python-send-receive 'python-shell-internal-send-string "23.3") |
| 1587 | |
| 1588 | (define-obsolete-function-alias |
| 1589 | 'python-send-string 'python-shell-internal-send-string "23.3") |
| 1590 | |
| 1591 | (defun python-shell-send-region (start end) |
| 1592 | "Send the region delimited by START and END to inferior Python process." |
| 1593 | (interactive "r") |
| 1594 | (python-shell-send-string (buffer-substring start end) nil t)) |
| 1595 | |
| 1596 | (defun python-shell-send-buffer () |
| 1597 | "Send the entire buffer to inferior Python process." |
| 1598 | (interactive) |
| 1599 | (save-restriction |
| 1600 | (widen) |
| 1601 | (python-shell-send-region (point-min) (point-max)))) |
| 1602 | |
| 1603 | (defun python-shell-send-defun (arg) |
| 1604 | "Send the current defun to inferior Python process. |
| 1605 | When argument ARG is non-nil sends the innermost defun." |
| 1606 | (interactive "P") |
| 1607 | (save-excursion |
| 1608 | (python-shell-send-region |
| 1609 | (progn |
| 1610 | (or (python-beginning-of-defun-function) |
| 1611 | (progn (beginning-of-line) (point-marker)))) |
| 1612 | (progn |
| 1613 | (or (python-end-of-defun-function) |
| 1614 | (progn (end-of-line) (point-marker))))))) |
| 1615 | |
| 1616 | (defun python-shell-send-file (file-name &optional process temp-file-name) |
| 1617 | "Send FILE-NAME to inferior Python PROCESS. |
| 1618 | If TEMP-FILE-NAME is passed then that file is used for processing |
| 1619 | instead, while internally the shell will continue to use |
| 1620 | FILE-NAME." |
| 1621 | (interactive "fFile to send: ") |
| 1622 | (let* ((process (or process (python-shell-get-or-create-process))) |
| 1623 | (temp-file-name (when temp-file-name |
| 1624 | (expand-file-name temp-file-name))) |
| 1625 | (file-name (or (expand-file-name file-name) temp-file-name))) |
| 1626 | (when (not file-name) |
| 1627 | (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil")) |
| 1628 | (python-shell-send-string |
| 1629 | (format |
| 1630 | (concat "__pyfile = open('''%s''');" |
| 1631 | "exec(compile(__pyfile.read(), '''%s''', 'exec'));" |
| 1632 | "__pyfile.close()") |
| 1633 | (or temp-file-name file-name) file-name) |
| 1634 | process))) |
| 1635 | |
| 1636 | (defun python-shell-switch-to-shell () |
| 1637 | "Switch to inferior Python process buffer." |
| 1638 | (interactive) |
| 1639 | (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t)) |
| 1640 | |
| 1641 | (defun python-shell-send-setup-code () |
| 1642 | "Send all setup code for shell. |
| 1643 | This function takes the list of setup code to send from the |
| 1644 | `python-shell-setup-codes' list." |
| 1645 | (let ((msg "Sent %s") |
| 1646 | (process (get-buffer-process (current-buffer)))) |
| 1647 | (accept-process-output process python-shell-send-setup-max-wait) |
| 1648 | (dolist (code python-shell-setup-codes) |
| 1649 | (when code |
| 1650 | (message (format msg code)) |
| 1651 | (python-shell-send-string |
| 1652 | (symbol-value code) process))))) |
| 1653 | |
| 1654 | (add-hook 'inferior-python-mode-hook |
| 1655 | #'python-shell-send-setup-code) |
| 1656 | |
| 1657 | \f |
| 1658 | ;;; Shell completion |
| 1659 | |
| 1660 | (defcustom python-shell-completion-setup-code |
| 1661 | "try: |
| 1662 | import readline |
| 1663 | except ImportError: |
| 1664 | def __COMPLETER_all_completions(text): [] |
| 1665 | else: |
| 1666 | import rlcompleter |
| 1667 | readline.set_completer(rlcompleter.Completer().complete) |
| 1668 | def __COMPLETER_all_completions(text): |
| 1669 | import sys |
| 1670 | completions = [] |
| 1671 | try: |
| 1672 | i = 0 |
| 1673 | while True: |
| 1674 | res = readline.get_completer()(text, i) |
| 1675 | if not res: break |
| 1676 | i += 1 |
| 1677 | completions.append(res) |
| 1678 | except NameError: |
| 1679 | pass |
| 1680 | return completions" |
| 1681 | "Code used to setup completion in inferior Python processes." |
| 1682 | :type 'string |
| 1683 | :group 'python) |
| 1684 | |
| 1685 | (defcustom python-shell-completion-string-code |
| 1686 | "';'.join(__COMPLETER_all_completions('''%s'''))\n" |
| 1687 | "Python code used to get a string of completions separated by semicolons." |
| 1688 | :type 'string |
| 1689 | :group 'python) |
| 1690 | |
| 1691 | (defcustom python-shell-completion-module-string-code "" |
| 1692 | "Python code used to get completions separated by semicolons for imports. |
| 1693 | |
| 1694 | For IPython v0.11, add the following line to |
| 1695 | `python-shell-completion-setup-code': |
| 1696 | |
| 1697 | from IPython.core.completerlib import module_completion |
| 1698 | |
| 1699 | and use the following as the value of this variable: |
| 1700 | |
| 1701 | ';'.join(module_completion('''%s'''))\n" |
| 1702 | :type 'string |
| 1703 | :group 'python) |
| 1704 | |
| 1705 | (defcustom python-shell-completion-pdb-string-code |
| 1706 | "';'.join(globals().keys() + locals().keys())" |
| 1707 | "Python code used to get completions separated by semicolons for [i]pdb." |
| 1708 | :type 'string |
| 1709 | :group 'python) |
| 1710 | |
| 1711 | (defun python-shell-completion--get-completions (input process completion-code) |
| 1712 | "Retrieve available completions for INPUT using PROCESS. |
| 1713 | Argument COMPLETION-CODE is the python code used to get |
| 1714 | completions on the current context." |
| 1715 | (with-current-buffer (process-buffer process) |
| 1716 | (let ((completions (python-shell-send-string-no-output |
| 1717 | (format completion-code input) process))) |
| 1718 | (when (> (length completions) 2) |
| 1719 | (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t))))) |
| 1720 | |
| 1721 | (defun python-shell-completion--do-completion-at-point (process) |
| 1722 | "Do completion at point for PROCESS." |
| 1723 | (with-syntax-table python-dotty-syntax-table |
| 1724 | (let* ((beg |
| 1725 | (save-excursion |
| 1726 | (let* ((paren-depth (car (syntax-ppss))) |
| 1727 | (syntax-string "w_") |
| 1728 | (syntax-list (string-to-syntax syntax-string))) |
| 1729 | ;; Stop scanning for the beginning of the completion subject |
| 1730 | ;; after the char before point matches a delimiter |
| 1731 | (while (member (car (syntax-after (1- (point)))) syntax-list) |
| 1732 | (skip-syntax-backward syntax-string) |
| 1733 | (when (or (equal (char-before) ?\)) |
| 1734 | (equal (char-before) ?\")) |
| 1735 | (forward-char -1)) |
| 1736 | (while (or |
| 1737 | ;; honor initial paren depth |
| 1738 | (> (car (syntax-ppss)) paren-depth) |
| 1739 | (python-info-ppss-context 'string)) |
| 1740 | (forward-char -1)))) |
| 1741 | (point))) |
| 1742 | (end (point)) |
| 1743 | (line (buffer-substring-no-properties (point-at-bol) end)) |
| 1744 | (input (buffer-substring-no-properties beg end)) |
| 1745 | ;; Get the last prompt for the inferior process buffer. This is |
| 1746 | ;; used for the completion code selection heuristic. |
| 1747 | (prompt |
| 1748 | (with-current-buffer (process-buffer process) |
| 1749 | (buffer-substring-no-properties |
| 1750 | (overlay-start comint-last-prompt-overlay) |
| 1751 | (overlay-end comint-last-prompt-overlay)))) |
| 1752 | (completion-context |
| 1753 | ;; Check wether a prompt matches a pdb string, an import statement |
| 1754 | ;; or just the standard prompt and use the correct |
| 1755 | ;; python-shell-completion-*-code string |
| 1756 | (cond ((and (> (length python-shell-completion-pdb-string-code) 0) |
| 1757 | (string-match |
| 1758 | (concat "^" python-shell-prompt-pdb-regexp) prompt)) |
| 1759 | 'pdb) |
| 1760 | ((and (> |
| 1761 | (length python-shell-completion-module-string-code) 0) |
| 1762 | (string-match |
| 1763 | (concat "^" python-shell-prompt-regexp) prompt) |
| 1764 | (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line)) |
| 1765 | 'import) |
| 1766 | ((string-match |
| 1767 | (concat "^" python-shell-prompt-regexp) prompt) |
| 1768 | 'default) |
| 1769 | (t nil))) |
| 1770 | (completion-code |
| 1771 | (case completion-context |
| 1772 | ('pdb python-shell-completion-pdb-string-code) |
| 1773 | ('import python-shell-completion-module-string-code) |
| 1774 | ('default python-shell-completion-string-code) |
| 1775 | (t nil))) |
| 1776 | (input |
| 1777 | (if (eq completion-context 'import) |
| 1778 | (replace-regexp-in-string "^[ \t]+" "" line) |
| 1779 | input)) |
| 1780 | (completions |
| 1781 | (and completion-code (> (length input) 0) |
| 1782 | (python-shell-completion--get-completions |
| 1783 | input process completion-code)))) |
| 1784 | (list beg end completions)))) |
| 1785 | |
| 1786 | (defun python-shell-completion-complete-at-point () |
| 1787 | "Perform completion at point in inferior Python process." |
| 1788 | (interactive) |
| 1789 | (and comint-last-prompt-overlay |
| 1790 | (> (point-marker) (overlay-end comint-last-prompt-overlay)) |
| 1791 | (python-shell-completion--do-completion-at-point |
| 1792 | (get-buffer-process (current-buffer))))) |
| 1793 | |
| 1794 | (defun python-shell-completion-complete-or-indent () |
| 1795 | "Complete or indent depending on the context. |
| 1796 | If content before pointer is all whitespace indent. If not try |
| 1797 | to complete." |
| 1798 | (interactive) |
| 1799 | (if (string-match "^[[:space:]]*$" |
| 1800 | (buffer-substring (comint-line-beginning-position) |
| 1801 | (point-marker))) |
| 1802 | (indent-for-tab-command) |
| 1803 | (completion-at-point))) |
| 1804 | |
| 1805 | \f |
| 1806 | ;;; PDB Track integration |
| 1807 | |
| 1808 | (defcustom python-pdbtrack-activate t |
| 1809 | "Non-nil makes python shell enable pdbtracking." |
| 1810 | :type 'boolean |
| 1811 | :group 'python |
| 1812 | :safe 'booleanp) |
| 1813 | |
| 1814 | (defcustom python-pdbtrack-stacktrace-info-regexp |
| 1815 | "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()" |
| 1816 | "Regular Expression matching stacktrace information. |
| 1817 | Used to extract the current line and module being inspected." |
| 1818 | :type 'string |
| 1819 | :group 'python |
| 1820 | :safe 'stringp) |
| 1821 | |
| 1822 | (defvar python-pdbtrack-tracked-buffer nil |
| 1823 | "Variable containing the value of the current tracked buffer. |
| 1824 | Never set this variable directly, use |
| 1825 | `python-pdbtrack-set-tracked-buffer' instead.") |
| 1826 | (make-variable-buffer-local 'python-pdbtrack-tracked-buffer) |
| 1827 | |
| 1828 | (defvar python-pdbtrack-buffers-to-kill nil |
| 1829 | "List of buffers to be deleted after tracking finishes.") |
| 1830 | (make-variable-buffer-local 'python-pdbtrack-buffers-to-kill) |
| 1831 | |
| 1832 | (defun python-pdbtrack-set-tracked-buffer (file-name) |
| 1833 | "Set the buffer for FILE-NAME as the tracked buffer. |
| 1834 | Internally it uses the `python-pdbtrack-tracked-buffer' variable. |
| 1835 | Returns the tracked buffer." |
| 1836 | (let ((file-buffer (get-file-buffer file-name))) |
| 1837 | (if file-buffer |
| 1838 | (setq python-pdbtrack-tracked-buffer file-buffer) |
| 1839 | (setq file-buffer (find-file-noselect file-name)) |
| 1840 | (when (not (member file-buffer python-pdbtrack-buffers-to-kill)) |
| 1841 | (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer))) |
| 1842 | file-buffer)) |
| 1843 | |
| 1844 | (defun python-pdbtrack-comint-output-filter-function (output) |
| 1845 | "Move overlay arrow to current pdb line in tracked buffer. |
| 1846 | Argument OUTPUT is a string with the output from the comint process." |
| 1847 | (when (and python-pdbtrack-activate (not (string= output ""))) |
| 1848 | (let* ((full-output (ansi-color-filter-apply |
| 1849 | (buffer-substring comint-last-input-end (point-max)))) |
| 1850 | (line-number) |
| 1851 | (file-name |
| 1852 | (with-temp-buffer |
| 1853 | (insert full-output) |
| 1854 | (goto-char (point-min)) |
| 1855 | ;; OK, this sucked but now it became a cool hack. The |
| 1856 | ;; stacktrace information normally is on the first line |
| 1857 | ;; but in some cases (like when doing a step-in) it is |
| 1858 | ;; on the second. |
| 1859 | (when (or (looking-at python-pdbtrack-stacktrace-info-regexp) |
| 1860 | (and |
| 1861 | (forward-line) |
| 1862 | (looking-at python-pdbtrack-stacktrace-info-regexp))) |
| 1863 | (setq line-number (string-to-number |
| 1864 | (match-string-no-properties 2))) |
| 1865 | (match-string-no-properties 1))))) |
| 1866 | (if (and file-name line-number) |
| 1867 | (let* ((tracked-buffer |
| 1868 | (python-pdbtrack-set-tracked-buffer file-name)) |
| 1869 | (shell-buffer (current-buffer)) |
| 1870 | (tracked-buffer-window (get-buffer-window tracked-buffer)) |
| 1871 | (tracked-buffer-line-pos)) |
| 1872 | (with-current-buffer tracked-buffer |
| 1873 | (set (make-local-variable 'overlay-arrow-string) "=>") |
| 1874 | (set (make-local-variable 'overlay-arrow-position) (make-marker)) |
| 1875 | (setq tracked-buffer-line-pos (progn |
| 1876 | (goto-char (point-min)) |
| 1877 | (forward-line (1- line-number)) |
| 1878 | (point-marker))) |
| 1879 | (when tracked-buffer-window |
| 1880 | (set-window-point |
| 1881 | tracked-buffer-window tracked-buffer-line-pos)) |
| 1882 | (set-marker overlay-arrow-position tracked-buffer-line-pos)) |
| 1883 | (pop-to-buffer tracked-buffer) |
| 1884 | (switch-to-buffer-other-window shell-buffer)) |
| 1885 | (when python-pdbtrack-tracked-buffer |
| 1886 | (with-current-buffer python-pdbtrack-tracked-buffer |
| 1887 | (set-marker overlay-arrow-position nil)) |
| 1888 | (mapc #'(lambda (buffer) |
| 1889 | (ignore-errors (kill-buffer buffer))) |
| 1890 | python-pdbtrack-buffers-to-kill) |
| 1891 | (setq python-pdbtrack-tracked-buffer nil |
| 1892 | python-pdbtrack-buffers-to-kill nil))))) |
| 1893 | output) |
| 1894 | |
| 1895 | \f |
| 1896 | ;;; Symbol completion |
| 1897 | |
| 1898 | (defun python-completion-complete-at-point () |
| 1899 | "Complete current symbol at point. |
| 1900 | For this to work the best as possible you should call |
| 1901 | `python-shell-send-buffer' from time to time so context in |
| 1902 | inferior python process is updated properly." |
| 1903 | (interactive) |
| 1904 | (let ((process (python-shell-get-process))) |
| 1905 | (if (not process) |
| 1906 | (error "Completion needs an inferior Python process running.") |
| 1907 | (python-shell-completion--do-completion-at-point process)))) |
| 1908 | |
| 1909 | (add-to-list 'debug-ignored-errors |
| 1910 | "^Completion needs an inferior Python process running.") |
| 1911 | |
| 1912 | \f |
| 1913 | ;;; Fill paragraph |
| 1914 | |
| 1915 | (defcustom python-fill-comment-function 'python-fill-comment |
| 1916 | "Function to fill comments. |
| 1917 | This is the function used by `python-fill-paragraph-function' to |
| 1918 | fill comments." |
| 1919 | :type 'symbol |
| 1920 | :group 'python |
| 1921 | :safe 'symbolp) |
| 1922 | |
| 1923 | (defcustom python-fill-string-function 'python-fill-string |
| 1924 | "Function to fill strings. |
| 1925 | This is the function used by `python-fill-paragraph-function' to |
| 1926 | fill strings." |
| 1927 | :type 'symbol |
| 1928 | :group 'python |
| 1929 | :safe 'symbolp) |
| 1930 | |
| 1931 | (defcustom python-fill-decorator-function 'python-fill-decorator |
| 1932 | "Function to fill decorators. |
| 1933 | This is the function used by `python-fill-paragraph-function' to |
| 1934 | fill decorators." |
| 1935 | :type 'symbol |
| 1936 | :group 'python |
| 1937 | :safe 'symbolp) |
| 1938 | |
| 1939 | (defcustom python-fill-paren-function 'python-fill-paren |
| 1940 | "Function to fill parens. |
| 1941 | This is the function used by `python-fill-paragraph-function' to |
| 1942 | fill parens." |
| 1943 | :type 'symbol |
| 1944 | :group 'python |
| 1945 | :safe 'symbolp) |
| 1946 | |
| 1947 | (defun python-fill-paragraph-function (&optional justify) |
| 1948 | "`fill-paragraph-function' handling multi-line strings and possibly comments. |
| 1949 | If any of the current line is in or at the end of a multi-line string, |
| 1950 | fill the string or the paragraph of it that point is in, preserving |
| 1951 | the string's indentation. |
| 1952 | Optional argument JUSTIFY defines if the paragraph should be justified." |
| 1953 | (interactive "P") |
| 1954 | (save-excursion |
| 1955 | (back-to-indentation) |
| 1956 | (cond |
| 1957 | ;; Comments |
| 1958 | ((funcall python-fill-comment-function justify)) |
| 1959 | ;; Strings/Docstrings |
| 1960 | ((save-excursion (skip-chars-forward "\"'uUrR") |
| 1961 | (python-info-ppss-context 'string)) |
| 1962 | (funcall python-fill-string-function justify)) |
| 1963 | ;; Decorators |
| 1964 | ((equal (char-after (save-excursion |
| 1965 | (back-to-indentation) |
| 1966 | (point-marker))) ?@) |
| 1967 | (funcall python-fill-decorator-function justify)) |
| 1968 | ;; Parens |
| 1969 | ((or (python-info-ppss-context 'paren) |
| 1970 | (looking-at (python-rx open-paren)) |
| 1971 | (save-excursion |
| 1972 | (skip-syntax-forward "^(" (line-end-position)) |
| 1973 | (looking-at (python-rx open-paren)))) |
| 1974 | (funcall python-fill-paren-function justify)) |
| 1975 | (t t)))) |
| 1976 | |
| 1977 | (defun python-fill-comment (&optional justify) |
| 1978 | "Comment fill function for `python-fill-paragraph-function'. |
| 1979 | JUSTIFY should be used (if applicable) as in `fill-paragraph'." |
| 1980 | (fill-comment-paragraph justify)) |
| 1981 | |
| 1982 | (defun python-fill-string (&optional justify) |
| 1983 | "String fill function for `python-fill-paragraph-function'. |
| 1984 | JUSTIFY should be used (if applicable) as in `fill-paragraph'." |
| 1985 | (let ((marker (point-marker)) |
| 1986 | (string-start-marker |
| 1987 | (progn |
| 1988 | (skip-chars-forward "\"'uUrR") |
| 1989 | (goto-char (python-info-ppss-context 'string)) |
| 1990 | (skip-chars-forward "\"'uUrR") |
| 1991 | (point-marker))) |
| 1992 | (reg-start (line-beginning-position)) |
| 1993 | (string-end-marker |
| 1994 | (progn |
| 1995 | (while (python-info-ppss-context 'string) |
| 1996 | (goto-char (1+ (point-marker)))) |
| 1997 | (skip-chars-backward "\"'") |
| 1998 | (point-marker))) |
| 1999 | (reg-end (line-end-position)) |
| 2000 | (fill-paragraph-function)) |
| 2001 | (save-restriction |
| 2002 | (narrow-to-region reg-start reg-end) |
| 2003 | (save-excursion |
| 2004 | (goto-char string-start-marker) |
| 2005 | (delete-region (point-marker) (progn |
| 2006 | (skip-syntax-forward "> ") |
| 2007 | (point-marker))) |
| 2008 | (goto-char string-end-marker) |
| 2009 | (delete-region (point-marker) (progn |
| 2010 | (skip-syntax-backward "> ") |
| 2011 | (point-marker))) |
| 2012 | (save-excursion |
| 2013 | (goto-char marker) |
| 2014 | (fill-paragraph justify)) |
| 2015 | ;; If there is a newline in the docstring lets put triple |
| 2016 | ;; quote in it's own line to follow pep 8 |
| 2017 | (when (save-excursion |
| 2018 | (re-search-backward "\n" string-start-marker t)) |
| 2019 | (newline) |
| 2020 | (newline-and-indent)) |
| 2021 | (fill-paragraph justify)))) t) |
| 2022 | |
| 2023 | (defun python-fill-decorator (&optional justify) |
| 2024 | "Decorator fill function for `python-fill-paragraph-function'. |
| 2025 | JUSTIFY should be used (if applicable) as in `fill-paragraph'." |
| 2026 | t) |
| 2027 | |
| 2028 | (defun python-fill-paren (&optional justify) |
| 2029 | "Paren fill function for `python-fill-paragraph-function'. |
| 2030 | JUSTIFY should be used (if applicable) as in `fill-paragraph'." |
| 2031 | (save-restriction |
| 2032 | (narrow-to-region (progn |
| 2033 | (while (python-info-ppss-context 'paren) |
| 2034 | (goto-char (1- (point-marker)))) |
| 2035 | (point-marker) |
| 2036 | (line-beginning-position)) |
| 2037 | (progn |
| 2038 | (when (not (python-info-ppss-context 'paren)) |
| 2039 | (end-of-line) |
| 2040 | (when (not (python-info-ppss-context 'paren)) |
| 2041 | (skip-syntax-backward "^)"))) |
| 2042 | (while (python-info-ppss-context 'paren) |
| 2043 | (goto-char (1+ (point-marker)))) |
| 2044 | (point-marker))) |
| 2045 | (let ((paragraph-start "\f\\|[ \t]*$") |
| 2046 | (paragraph-separate ",") |
| 2047 | (fill-paragraph-function)) |
| 2048 | (goto-char (point-min)) |
| 2049 | (fill-paragraph justify)) |
| 2050 | (while (not (eobp)) |
| 2051 | (forward-line 1) |
| 2052 | (python-indent-line) |
| 2053 | (goto-char (line-end-position)))) t) |
| 2054 | |
| 2055 | \f |
| 2056 | ;;; Skeletons |
| 2057 | |
| 2058 | (defcustom python-skeleton-autoinsert nil |
| 2059 | "Non-nil means template skeletons will be automagically inserted. |
| 2060 | This happens when pressing \"if<SPACE>\", for example, to prompt for |
| 2061 | the if condition." |
| 2062 | :type 'boolean |
| 2063 | :group 'python |
| 2064 | :safe 'booleanp) |
| 2065 | |
| 2066 | (defvar python-skeleton-available '() |
| 2067 | "Internal list of available skeletons.") |
| 2068 | |
| 2069 | (define-abbrev-table 'python-mode-abbrev-table () |
| 2070 | "Abbrev table for Python mode." |
| 2071 | :case-fixed t |
| 2072 | ;; Allow / inside abbrevs. |
| 2073 | :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*" |
| 2074 | ;; Only expand in code. |
| 2075 | :enable-function (lambda () |
| 2076 | (and |
| 2077 | (not (or (python-info-ppss-context 'string) |
| 2078 | (python-info-ppss-context 'comment))) |
| 2079 | python-skeleton-autoinsert))) |
| 2080 | |
| 2081 | (defmacro python-skeleton-define (name doc &rest skel) |
| 2082 | "Define a `python-mode' skeleton using NAME DOC and SKEL. |
| 2083 | The skeleton will be bound to python-skeleton-NAME and will |
| 2084 | be added to `python-mode-abbrev-table'." |
| 2085 | (let* ((name (symbol-name name)) |
| 2086 | (function-name (intern (concat "python-skeleton-" name)))) |
| 2087 | `(progn |
| 2088 | (define-abbrev python-mode-abbrev-table ,name "" ',function-name) |
| 2089 | (setq python-skeleton-available |
| 2090 | (cons ',function-name python-skeleton-available)) |
| 2091 | (define-skeleton ,function-name |
| 2092 | ,(or doc |
| 2093 | (format "Insert %s statement." name)) |
| 2094 | ,@skel)))) |
| 2095 | (put 'python-skeleton-define 'lisp-indent-function 2) |
| 2096 | |
| 2097 | (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel) |
| 2098 | "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL. |
| 2099 | The skeleton will be bound to python-skeleton-NAME." |
| 2100 | (let* ((name (symbol-name name)) |
| 2101 | (function-name (intern (concat "python-skeleton--" name))) |
| 2102 | (msg (format |
| 2103 | "Add '%s' clause? " name))) |
| 2104 | (when (not skel) |
| 2105 | (setq skel |
| 2106 | `(< ,(format "%s:" name) \n \n |
| 2107 | > _ \n))) |
| 2108 | `(define-skeleton ,function-name |
| 2109 | ,(or doc |
| 2110 | (format "Auxiliary skeleton for %s statement." name)) |
| 2111 | nil |
| 2112 | (unless (y-or-n-p ,msg) |
| 2113 | (signal 'quit t)) |
| 2114 | ,@skel))) |
| 2115 | (put 'python-define-auxiliary-skeleton 'lisp-indent-function 2) |
| 2116 | |
| 2117 | (python-define-auxiliary-skeleton else nil) |
| 2118 | |
| 2119 | (python-define-auxiliary-skeleton except nil) |
| 2120 | |
| 2121 | (python-define-auxiliary-skeleton finally nil) |
| 2122 | |
| 2123 | (python-skeleton-define if nil |
| 2124 | "Condition: " |
| 2125 | "if " str ":" \n |
| 2126 | _ \n |
| 2127 | ("other condition, %s: " |
| 2128 | < |
| 2129 | "elif " str ":" \n |
| 2130 | > _ \n nil) |
| 2131 | '(python-skeleton--else) | ^) |
| 2132 | |
| 2133 | (python-skeleton-define while nil |
| 2134 | "Condition: " |
| 2135 | "while " str ":" \n |
| 2136 | > _ \n |
| 2137 | '(python-skeleton--else) | ^) |
| 2138 | |
| 2139 | (python-skeleton-define for nil |
| 2140 | "Iteration spec: " |
| 2141 | "for " str ":" \n |
| 2142 | > _ \n |
| 2143 | '(python-skeleton--else) | ^) |
| 2144 | |
| 2145 | (python-skeleton-define try nil |
| 2146 | nil |
| 2147 | "try:" \n |
| 2148 | > _ \n |
| 2149 | ("Exception, %s: " |
| 2150 | < |
| 2151 | "except " str ":" \n |
| 2152 | > _ \n nil) |
| 2153 | resume: |
| 2154 | '(python-skeleton--except) |
| 2155 | '(python-skeleton--else) |
| 2156 | '(python-skeleton--finally) | ^) |
| 2157 | |
| 2158 | (python-skeleton-define def nil |
| 2159 | "Function name: " |
| 2160 | "def " str " (" ("Parameter, %s: " |
| 2161 | (unless (equal ?\( (char-before)) ", ") |
| 2162 | str) "):" \n |
| 2163 | "\"\"\"" - "\"\"\"" \n |
| 2164 | > _ \n) |
| 2165 | |
| 2166 | (python-skeleton-define class nil |
| 2167 | "Class name: " |
| 2168 | "class " str " (" ("Inheritance, %s: " |
| 2169 | (unless (equal ?\( (char-before)) ", ") |
| 2170 | str) |
| 2171 | & ")" | -2 |
| 2172 | ":" \n |
| 2173 | "\"\"\"" - "\"\"\"" \n |
| 2174 | > _ \n) |
| 2175 | |
| 2176 | (defun python-skeleton-add-menu-items () |
| 2177 | "Add menu items to Python->Skeletons menu." |
| 2178 | (let ((skeletons (sort python-skeleton-available 'string<)) |
| 2179 | (items)) |
| 2180 | (dolist (skeleton skeletons) |
| 2181 | (easy-menu-add-item |
| 2182 | nil '("Python" "Skeletons") |
| 2183 | `[,(format |
| 2184 | "Insert %s" (caddr (split-string (symbol-name skeleton) "-"))) |
| 2185 | ,skeleton t])))) |
| 2186 | \f |
| 2187 | ;;; FFAP |
| 2188 | |
| 2189 | (defcustom python-ffap-setup-code |
| 2190 | "def __FFAP_get_module_path(module): |
| 2191 | try: |
| 2192 | import os |
| 2193 | path = __import__(module).__file__ |
| 2194 | if path[-4:] == '.pyc' and os.path.exists(path[0:-1]): |
| 2195 | path = path[:-1] |
| 2196 | return path |
| 2197 | except: |
| 2198 | return ''" |
| 2199 | "Python code to get a module path." |
| 2200 | :type 'string |
| 2201 | :group 'python) |
| 2202 | |
| 2203 | (defcustom python-ffap-string-code |
| 2204 | "__FFAP_get_module_path('''%s''')\n" |
| 2205 | "Python code used to get a string with the path of a module." |
| 2206 | :type 'string |
| 2207 | :group 'python) |
| 2208 | |
| 2209 | (defun python-ffap-module-path (module) |
| 2210 | "Function for `ffap-alist' to return path for MODULE." |
| 2211 | (let ((process (or |
| 2212 | (and (eq major-mode 'inferior-python-mode) |
| 2213 | (get-buffer-process (current-buffer))) |
| 2214 | (python-shell-get-process)))) |
| 2215 | (if (not process) |
| 2216 | nil |
| 2217 | (let ((module-file |
| 2218 | (python-shell-send-string-no-output |
| 2219 | (format python-ffap-string-code module) process))) |
| 2220 | (when module-file |
| 2221 | (substring-no-properties module-file 1 -1)))))) |
| 2222 | |
| 2223 | (eval-after-load "ffap" |
| 2224 | '(progn |
| 2225 | (push '(python-mode . python-ffap-module-path) ffap-alist) |
| 2226 | (push '(inferior-python-mode . python-ffap-module-path) ffap-alist))) |
| 2227 | |
| 2228 | \f |
| 2229 | ;;; Code check |
| 2230 | |
| 2231 | (defcustom python-check-command |
| 2232 | "pyflakes" |
| 2233 | "Command used to check a Python file." |
| 2234 | :type 'string |
| 2235 | :group 'python) |
| 2236 | |
| 2237 | (defcustom python-check-buffer-name |
| 2238 | "*Python check: %s*" |
| 2239 | "Buffer name used for check commands." |
| 2240 | :type 'string |
| 2241 | :group 'python) |
| 2242 | |
| 2243 | (defvar python-check-custom-command nil |
| 2244 | "Internal use.") |
| 2245 | |
| 2246 | (defun python-check (command) |
| 2247 | "Check a Python file (default current buffer's file). |
| 2248 | Runs COMMAND, a shell command, as if by `compile'. See |
| 2249 | `python-check-command' for the default." |
| 2250 | (interactive |
| 2251 | (list (read-string "Check command: " |
| 2252 | (or python-check-custom-command |
| 2253 | (concat python-check-command " " |
| 2254 | (shell-quote-argument |
| 2255 | (or |
| 2256 | (let ((name (buffer-file-name))) |
| 2257 | (and name |
| 2258 | (file-name-nondirectory name))) |
| 2259 | ""))))))) |
| 2260 | (setq python-check-custom-command command) |
| 2261 | (save-some-buffers (not compilation-ask-about-save) nil) |
| 2262 | (let ((process-environment (python-shell-calculate-process-environment)) |
| 2263 | (exec-path (python-shell-calculate-exec-path))) |
| 2264 | (compilation-start command nil |
| 2265 | (lambda (mode-name) |
| 2266 | (format python-check-buffer-name command))))) |
| 2267 | |
| 2268 | \f |
| 2269 | ;;; Eldoc |
| 2270 | |
| 2271 | (defcustom python-eldoc-setup-code |
| 2272 | "def __PYDOC_get_help(obj): |
| 2273 | try: |
| 2274 | import inspect |
| 2275 | if hasattr(obj, 'startswith'): |
| 2276 | obj = eval(obj, globals()) |
| 2277 | doc = inspect.getdoc(obj) |
| 2278 | if not doc and callable(obj): |
| 2279 | target = None |
| 2280 | if inspect.isclass(obj) and hasattr(obj, '__init__'): |
| 2281 | target = obj.__init__ |
| 2282 | objtype = 'class' |
| 2283 | else: |
| 2284 | target = obj |
| 2285 | objtype = 'def' |
| 2286 | if target: |
| 2287 | args = inspect.formatargspec( |
| 2288 | *inspect.getargspec(target) |
| 2289 | ) |
| 2290 | name = obj.__name__ |
| 2291 | doc = '{objtype} {name}{args}'.format( |
| 2292 | objtype=objtype, name=name, args=args |
| 2293 | ) |
| 2294 | else: |
| 2295 | doc = doc.splitlines()[0] |
| 2296 | except: |
| 2297 | doc = '' |
| 2298 | try: |
| 2299 | exec('print doc') |
| 2300 | except SyntaxError: |
| 2301 | print(doc)" |
| 2302 | "Python code to setup documentation retrieval." |
| 2303 | :type 'string |
| 2304 | :group 'python) |
| 2305 | |
| 2306 | (defcustom python-eldoc-string-code |
| 2307 | "__PYDOC_get_help('''%s''')\n" |
| 2308 | "Python code used to get a string with the documentation of an object." |
| 2309 | :type 'string |
| 2310 | :group 'python) |
| 2311 | |
| 2312 | (defun python-eldoc--get-doc-at-point (&optional force-input force-process) |
| 2313 | "Internal implementation to get documentation at point. |
| 2314 | If not FORCE-INPUT is passed then what `current-word' returns |
| 2315 | will be used. If not FORCE-PROCESS is passed what |
| 2316 | `python-shell-get-process' returns is used." |
| 2317 | (let ((process (or force-process (python-shell-get-process)))) |
| 2318 | (if (not process) |
| 2319 | "Eldoc needs an inferior Python process running." |
| 2320 | (let* ((current-defun (python-info-current-defun)) |
| 2321 | (input (or force-input |
| 2322 | (with-syntax-table python-dotty-syntax-table |
| 2323 | (if (not current-defun) |
| 2324 | (current-word) |
| 2325 | (concat current-defun "." (current-word)))))) |
| 2326 | (ppss (syntax-ppss)) |
| 2327 | (help (when (and |
| 2328 | input |
| 2329 | (not (string= input (concat current-defun "."))) |
| 2330 | (not (or (python-info-ppss-context 'string ppss) |
| 2331 | (python-info-ppss-context 'comment ppss)))) |
| 2332 | (when (string-match |
| 2333 | (concat |
| 2334 | (regexp-quote (concat current-defun ".")) |
| 2335 | "self\\.") input) |
| 2336 | (with-temp-buffer |
| 2337 | (insert input) |
| 2338 | (goto-char (point-min)) |
| 2339 | (forward-word) |
| 2340 | (forward-char) |
| 2341 | (delete-region |
| 2342 | (point-marker) (search-forward "self.")) |
| 2343 | (setq input (buffer-substring |
| 2344 | (point-min) (point-max))))) |
| 2345 | (python-shell-send-string-no-output |
| 2346 | (format python-eldoc-string-code input) process)))) |
| 2347 | (with-current-buffer (process-buffer process) |
| 2348 | (when comint-last-prompt-overlay |
| 2349 | (delete-region comint-last-input-end |
| 2350 | (overlay-start comint-last-prompt-overlay)))) |
| 2351 | (when (and help |
| 2352 | (not (string= help "\n"))) |
| 2353 | help))))) |
| 2354 | |
| 2355 | (defun python-eldoc-function () |
| 2356 | "`eldoc-documentation-function' for Python. |
| 2357 | For this to work the best as possible you should call |
| 2358 | `python-shell-send-buffer' from time to time so context in |
| 2359 | inferior python process is updated properly." |
| 2360 | (python-eldoc--get-doc-at-point)) |
| 2361 | |
| 2362 | (defun python-eldoc-at-point (symbol) |
| 2363 | "Get help on SYMBOL using `help'. |
| 2364 | Interactively, prompt for symbol." |
| 2365 | (interactive |
| 2366 | (let ((symbol (with-syntax-table python-dotty-syntax-table |
| 2367 | (current-word))) |
| 2368 | (enable-recursive-minibuffers t)) |
| 2369 | (list (read-string (if symbol |
| 2370 | (format "Describe symbol (default %s): " symbol) |
| 2371 | "Describe symbol: ") |
| 2372 | nil nil symbol)))) |
| 2373 | (let ((process (python-shell-get-process))) |
| 2374 | (if (not process) |
| 2375 | (message "Eldoc needs an inferior Python process running.") |
| 2376 | (message (python-eldoc--get-doc-at-point symbol process))))) |
| 2377 | |
| 2378 | \f |
| 2379 | ;;; Imenu |
| 2380 | |
| 2381 | (defcustom python-imenu-include-defun-type t |
| 2382 | "Non-nil make imenu items to include its type." |
| 2383 | :type 'boolean |
| 2384 | :group 'python |
| 2385 | :safe 'booleanp) |
| 2386 | |
| 2387 | (defcustom python-imenu-make-tree t |
| 2388 | "Non-nil make imenu to build a tree menu. |
| 2389 | Set to nil for speed." |
| 2390 | :type 'boolean |
| 2391 | :group 'python |
| 2392 | :safe 'booleanp) |
| 2393 | |
| 2394 | (defcustom python-imenu-subtree-root-label "<Jump to %s>" |
| 2395 | "Label displayed to navigate to root from a subtree. |
| 2396 | It can contain a \"%s\" which will be replaced with the root name." |
| 2397 | :type 'string |
| 2398 | :group 'python |
| 2399 | :safe 'stringp) |
| 2400 | |
| 2401 | (defvar python-imenu-index-alist nil |
| 2402 | "Calculated index tree for imenu.") |
| 2403 | |
| 2404 | (defun python-imenu-tree-assoc (keylist tree) |
| 2405 | "Using KEYLIST traverse TREE." |
| 2406 | (if keylist |
| 2407 | (python-imenu-tree-assoc (cdr keylist) |
| 2408 | (ignore-errors (assoc (car keylist) tree))) |
| 2409 | tree)) |
| 2410 | |
| 2411 | (defun python-imenu-make-element-tree (element-list full-element plain-index) |
| 2412 | "Make a tree from plain alist of module names. |
| 2413 | ELEMENT-LIST is the defun name splitted by \".\" and FULL-ELEMENT |
| 2414 | is the same thing, the difference is that FULL-ELEMENT remains |
| 2415 | untouched in all recursive calls. |
| 2416 | Argument PLAIN-INDEX is the calculated plain index used to build the tree." |
| 2417 | (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist)) |
| 2418 | (when element-list |
| 2419 | (let* ((subelement-point (cdr (assoc |
| 2420 | (mapconcat #'identity full-element ".") |
| 2421 | plain-index))) |
| 2422 | (subelement-name (car element-list)) |
| 2423 | (subelement-position (python-util-position |
| 2424 | subelement-name full-element)) |
| 2425 | (subelement-path (when subelement-position |
| 2426 | (butlast |
| 2427 | full-element |
| 2428 | (- (length full-element) |
| 2429 | subelement-position))))) |
| 2430 | (let ((path-ref (python-imenu-tree-assoc subelement-path |
| 2431 | python-imenu-index-alist))) |
| 2432 | (if (not path-ref) |
| 2433 | (push (cons subelement-name subelement-point) |
| 2434 | python-imenu-index-alist) |
| 2435 | (when (not (listp (cdr path-ref))) |
| 2436 | ;; Modifiy root cdr to be a list |
| 2437 | (setcdr path-ref |
| 2438 | (list (cons (format python-imenu-subtree-root-label |
| 2439 | (car path-ref)) |
| 2440 | (cdr (assoc |
| 2441 | (mapconcat #'identity |
| 2442 | subelement-path ".") |
| 2443 | plain-index)))))) |
| 2444 | (when (not (assoc subelement-name path-ref)) |
| 2445 | (push (cons subelement-name subelement-point) (cdr path-ref)))))) |
| 2446 | (python-imenu-make-element-tree (cdr element-list) |
| 2447 | full-element plain-index)))) |
| 2448 | |
| 2449 | (defun python-imenu-make-tree (index) |
| 2450 | "Build the imenu alist tree from plain INDEX. |
| 2451 | |
| 2452 | The idea of this function is that given the alist: |
| 2453 | |
| 2454 | '((\"Test\" . 100) |
| 2455 | (\"Test.__init__\" . 200) |
| 2456 | (\"Test.some_method\" . 300) |
| 2457 | (\"Test.some_method.another\" . 400) |
| 2458 | (\"Test.something_else\" . 500) |
| 2459 | (\"test\" . 600) |
| 2460 | (\"test.reprint\" . 700) |
| 2461 | (\"test.reprint\" . 800)) |
| 2462 | |
| 2463 | This tree gets built: |
| 2464 | |
| 2465 | '((\"Test\" . ((\"jump to...\" . 100) |
| 2466 | (\"__init__\" . 200) |
| 2467 | (\"some_method\" . ((\"jump to...\" . 300) |
| 2468 | (\"another\" . 400))) |
| 2469 | (\"something_else\" . 500))) |
| 2470 | (\"test\" . ((\"jump to...\" . 600) |
| 2471 | (\"reprint\" . 700) |
| 2472 | (\"reprint\" . 800)))) |
| 2473 | |
| 2474 | Internally it uses `python-imenu-make-element-tree' to create all |
| 2475 | branches for each element." |
| 2476 | (setq python-imenu-index-alist nil) |
| 2477 | (mapc (lambda (element) |
| 2478 | (python-imenu-make-element-tree element element index)) |
| 2479 | (mapcar (lambda (element) |
| 2480 | (split-string (car element) "\\." t)) index)) |
| 2481 | python-imenu-index-alist) |
| 2482 | |
| 2483 | (defun python-imenu-create-index () |
| 2484 | "`imenu-create-index-function' for Python." |
| 2485 | (let ((index |
| 2486 | (python-nav-list-defun-positions python-imenu-include-defun-type))) |
| 2487 | (if python-imenu-make-tree |
| 2488 | (python-imenu-make-tree index) |
| 2489 | index))) |
| 2490 | |
| 2491 | \f |
| 2492 | ;;; Misc helpers |
| 2493 | |
| 2494 | (defun python-info-current-defun (&optional include-type) |
| 2495 | "Return name of surrounding function with Python compatible dotty syntax. |
| 2496 | Optional argument INCLUDE-TYPE indicates to include the type of the defun. |
| 2497 | This function is compatible to be used as |
| 2498 | `add-log-current-defun-function' since it returns nil if point is |
| 2499 | not inside a defun." |
| 2500 | (let ((names '()) |
| 2501 | (min-indent) |
| 2502 | (first-run t)) |
| 2503 | (save-restriction |
| 2504 | (widen) |
| 2505 | (save-excursion |
| 2506 | (goto-char (line-end-position)) |
| 2507 | (python-util-forward-comment -1) |
| 2508 | (setq min-indent (current-indentation)) |
| 2509 | (while (python-beginning-of-defun-function 1 t) |
| 2510 | (when (or (< (current-indentation) min-indent) |
| 2511 | first-run) |
| 2512 | (setq first-run nil) |
| 2513 | (setq min-indent (current-indentation)) |
| 2514 | (looking-at python-nav-beginning-of-defun-regexp) |
| 2515 | (setq names (cons |
| 2516 | (if (not include-type) |
| 2517 | (match-string-no-properties 1) |
| 2518 | (mapconcat 'identity |
| 2519 | (split-string |
| 2520 | (match-string-no-properties 0)) " ")) |
| 2521 | names)))))) |
| 2522 | (when names |
| 2523 | (mapconcat (lambda (string) string) names ".")))) |
| 2524 | |
| 2525 | (defun python-info-closing-block () |
| 2526 | "Return the point of the block the current line closes." |
| 2527 | (let ((closing-word (save-excursion |
| 2528 | (back-to-indentation) |
| 2529 | (current-word))) |
| 2530 | (indentation (current-indentation))) |
| 2531 | (when (member closing-word python-indent-dedenters) |
| 2532 | (save-excursion |
| 2533 | (forward-line -1) |
| 2534 | (while (and (> (current-indentation) indentation) |
| 2535 | (not (bobp)) |
| 2536 | (not (back-to-indentation)) |
| 2537 | (forward-line -1))) |
| 2538 | (back-to-indentation) |
| 2539 | (cond |
| 2540 | ((not (equal indentation (current-indentation))) nil) |
| 2541 | ((string= closing-word "elif") |
| 2542 | (when (member (current-word) '("if" "elif")) |
| 2543 | (point-marker))) |
| 2544 | ((string= closing-word "else") |
| 2545 | (when (member (current-word) '("if" "elif" "except" "for" "while")) |
| 2546 | (point-marker))) |
| 2547 | ((string= closing-word "except") |
| 2548 | (when (member (current-word) '("try")) |
| 2549 | (point-marker))) |
| 2550 | ((string= closing-word "finally") |
| 2551 | (when (member (current-word) '("except" "else")) |
| 2552 | (point-marker)))))))) |
| 2553 | |
| 2554 | (defun python-info-line-ends-backslash-p (&optional line-number) |
| 2555 | "Return non-nil if current line ends with backslash. |
| 2556 | With optional argument LINE-NUMBER, check that line instead." |
| 2557 | (save-excursion |
| 2558 | (save-restriction |
| 2559 | (widen) |
| 2560 | (when line-number |
| 2561 | (goto-char line-number)) |
| 2562 | (while (and (not (eobp)) |
| 2563 | (goto-char (line-end-position)) |
| 2564 | (python-info-ppss-context 'paren) |
| 2565 | (not (equal (char-before (point)) ?\\))) |
| 2566 | (forward-line 1)) |
| 2567 | (when (equal (char-before) ?\\) |
| 2568 | (point-marker))))) |
| 2569 | |
| 2570 | (defun python-info-beginning-of-backlash (&optional line-number) |
| 2571 | "Return the point where the backlashed line starts." |
| 2572 | (save-excursion |
| 2573 | (save-restriction |
| 2574 | (widen) |
| 2575 | (when line-number |
| 2576 | (goto-char line-number)) |
| 2577 | (when (python-info-line-ends-backslash-p) |
| 2578 | (while (save-excursion |
| 2579 | (goto-char (line-beginning-position)) |
| 2580 | (python-info-ppss-context 'paren)) |
| 2581 | (forward-line -1)) |
| 2582 | (back-to-indentation) |
| 2583 | (point-marker))))) |
| 2584 | |
| 2585 | (defun python-info-continuation-line-p () |
| 2586 | "Check if current line is continuation of another. |
| 2587 | When current line is continuation of another return the point |
| 2588 | where the continued line ends." |
| 2589 | (save-excursion |
| 2590 | (save-restriction |
| 2591 | (widen) |
| 2592 | (let* ((context-type (progn |
| 2593 | (back-to-indentation) |
| 2594 | (python-info-ppss-context-type))) |
| 2595 | (line-start (line-number-at-pos)) |
| 2596 | (context-start (when context-type |
| 2597 | (python-info-ppss-context context-type)))) |
| 2598 | (cond ((equal context-type 'paren) |
| 2599 | ;; Lines inside a paren are always a continuation line |
| 2600 | ;; (except the first one). |
| 2601 | (when (equal (python-info-ppss-context-type) 'paren) |
| 2602 | (python-util-forward-comment -1) |
| 2603 | (python-util-forward-comment -1) |
| 2604 | (point-marker))) |
| 2605 | ((or (equal context-type 'comment) |
| 2606 | (equal context-type 'string)) |
| 2607 | ;; move forward an roll again |
| 2608 | (goto-char context-start) |
| 2609 | (python-util-forward-comment) |
| 2610 | (python-info-continuation-line-p)) |
| 2611 | (t |
| 2612 | ;; Not within a paren, string or comment, the only way we are |
| 2613 | ;; dealing with a continuation line is that previous line |
| 2614 | ;; contains a backslash, and this can only be the previous line |
| 2615 | ;; from current |
| 2616 | (back-to-indentation) |
| 2617 | (python-util-forward-comment -1) |
| 2618 | (python-util-forward-comment -1) |
| 2619 | (when (and (equal (1- line-start) (line-number-at-pos)) |
| 2620 | (python-info-line-ends-backslash-p)) |
| 2621 | (point-marker)))))))) |
| 2622 | |
| 2623 | (defun python-info-block-continuation-line-p () |
| 2624 | "Return non-nil if current line is a continuation of a block." |
| 2625 | (save-excursion |
| 2626 | (when (python-info-continuation-line-p) |
| 2627 | (forward-line -1) |
| 2628 | (back-to-indentation) |
| 2629 | (when (looking-at (python-rx block-start)) |
| 2630 | (point-marker))))) |
| 2631 | |
| 2632 | (defun python-info-assignment-continuation-line-p () |
| 2633 | "Check if current line is a continuation of an assignment. |
| 2634 | When current line is continuation of another with an assignment |
| 2635 | return the point of the first non-blank character after the |
| 2636 | operator." |
| 2637 | (save-excursion |
| 2638 | (when (python-info-continuation-line-p) |
| 2639 | (forward-line -1) |
| 2640 | (back-to-indentation) |
| 2641 | (when (and (not (looking-at (python-rx block-start))) |
| 2642 | (and (re-search-forward (python-rx not-simple-operator |
| 2643 | assignment-operator |
| 2644 | not-simple-operator) |
| 2645 | (line-end-position) t) |
| 2646 | (not (or (python-info-ppss-context 'string) |
| 2647 | (python-info-ppss-context 'paren) |
| 2648 | (python-info-ppss-context 'comment))))) |
| 2649 | (skip-syntax-forward "\s") |
| 2650 | (point-marker))))) |
| 2651 | |
| 2652 | (defun python-info-ppss-context (type &optional syntax-ppss) |
| 2653 | "Return non-nil if point is on TYPE using SYNTAX-PPSS. |
| 2654 | TYPE can be 'comment, 'string or 'paren. It returns the start |
| 2655 | character address of the specified TYPE." |
| 2656 | (let ((ppss (or syntax-ppss (syntax-ppss)))) |
| 2657 | (case type |
| 2658 | ('comment |
| 2659 | (and (nth 4 ppss) |
| 2660 | (nth 8 ppss))) |
| 2661 | ('string |
| 2662 | (nth 8 ppss)) |
| 2663 | ('paren |
| 2664 | (nth 1 ppss)) |
| 2665 | (t nil)))) |
| 2666 | |
| 2667 | (defun python-info-ppss-context-type (&optional syntax-ppss) |
| 2668 | "Return the context type using SYNTAX-PPSS. |
| 2669 | The type returned can be 'comment, 'string or 'paren." |
| 2670 | (let ((ppss (or syntax-ppss (syntax-ppss)))) |
| 2671 | (cond |
| 2672 | ((and (nth 4 ppss) |
| 2673 | (nth 8 ppss)) |
| 2674 | 'comment) |
| 2675 | ((nth 8 ppss) |
| 2676 | 'string) |
| 2677 | ((nth 1 ppss) |
| 2678 | 'paren) |
| 2679 | (t nil)))) |
| 2680 | |
| 2681 | \f |
| 2682 | ;;; Utility functions |
| 2683 | |
| 2684 | (defun python-util-position (item seq) |
| 2685 | "Find the first occurrence of ITEM in SEQ. |
| 2686 | Return the index of the matching item, or nil if not found." |
| 2687 | (let ((member-result (member item seq))) |
| 2688 | (when member-result |
| 2689 | (- (length seq) (length member-result))))) |
| 2690 | |
| 2691 | ;; Stolen from org-mode |
| 2692 | (defun python-util-clone-local-variables (from-buffer &optional regexp) |
| 2693 | "Clone local variables from FROM-BUFFER. |
| 2694 | Optional argument REGEXP selects variables to clone and defaults |
| 2695 | to \"^python-\"." |
| 2696 | (mapc |
| 2697 | (lambda (pair) |
| 2698 | (and (symbolp (car pair)) |
| 2699 | (string-match (or regexp "^python-") |
| 2700 | (symbol-name (car pair))) |
| 2701 | (set (make-local-variable (car pair)) |
| 2702 | (cdr pair)))) |
| 2703 | (buffer-local-variables from-buffer))) |
| 2704 | |
| 2705 | (defun python-util-forward-comment (&optional direction) |
| 2706 | "Python mode specific version of `forward-comment'." |
| 2707 | (let ((comment-start (python-info-ppss-context 'comment)) |
| 2708 | (factor (if (< (or direction 0) 0) |
| 2709 | -99999 |
| 2710 | 99999))) |
| 2711 | (when comment-start |
| 2712 | (goto-char comment-start)) |
| 2713 | (forward-comment factor))) |
| 2714 | |
| 2715 | \f |
| 2716 | ;;;###autoload |
| 2717 | (define-derived-mode python-mode fundamental-mode "Python" |
| 2718 | "Major mode for editing Python files. |
| 2719 | |
| 2720 | \\{python-mode-map} |
| 2721 | Entry to this mode calls the value of `python-mode-hook' |
| 2722 | if that value is non-nil." |
| 2723 | (set (make-local-variable 'tab-width) 8) |
| 2724 | (set (make-local-variable 'indent-tabs-mode) nil) |
| 2725 | |
| 2726 | (set (make-local-variable 'comment-start) "# ") |
| 2727 | (set (make-local-variable 'comment-start-skip) "#+\\s-*") |
| 2728 | |
| 2729 | (set (make-local-variable 'parse-sexp-lookup-properties) t) |
| 2730 | (set (make-local-variable 'parse-sexp-ignore-comments) t) |
| 2731 | |
| 2732 | (set (make-local-variable 'font-lock-defaults) |
| 2733 | '(python-font-lock-keywords |
| 2734 | nil nil nil nil |
| 2735 | (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords))) |
| 2736 | |
| 2737 | (set (make-local-variable 'indent-line-function) |
| 2738 | #'python-indent-line-function) |
| 2739 | (set (make-local-variable 'indent-region-function) #'python-indent-region) |
| 2740 | |
| 2741 | (set (make-local-variable 'paragraph-start) "\\s-*$") |
| 2742 | (set (make-local-variable 'fill-paragraph-function) |
| 2743 | 'python-fill-paragraph-function) |
| 2744 | |
| 2745 | (set (make-local-variable 'beginning-of-defun-function) |
| 2746 | #'python-beginning-of-defun-function) |
| 2747 | (set (make-local-variable 'end-of-defun-function) |
| 2748 | #'python-end-of-defun-function) |
| 2749 | |
| 2750 | (add-hook 'completion-at-point-functions |
| 2751 | 'python-completion-complete-at-point nil 'local) |
| 2752 | |
| 2753 | (setq imenu-create-index-function #'python-imenu-create-index) |
| 2754 | |
| 2755 | (set (make-local-variable 'add-log-current-defun-function) |
| 2756 | #'python-info-current-defun) |
| 2757 | |
| 2758 | (set (make-local-variable 'skeleton-further-elements) |
| 2759 | '((abbrev-mode nil) |
| 2760 | (< '(backward-delete-char-untabify (min python-indent-offset |
| 2761 | (current-column)))) |
| 2762 | (^ '(- (1+ (current-indentation)))))) |
| 2763 | |
| 2764 | (set (make-local-variable 'eldoc-documentation-function) |
| 2765 | #'python-eldoc-function) |
| 2766 | |
| 2767 | (add-to-list 'hs-special-modes-alist |
| 2768 | `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#" |
| 2769 | ,(lambda (arg) |
| 2770 | (python-end-of-defun-function)) nil)) |
| 2771 | |
| 2772 | (set (make-local-variable 'mode-require-final-newline) t) |
| 2773 | |
| 2774 | (set (make-local-variable 'outline-regexp) |
| 2775 | (python-rx (* space) block-start)) |
| 2776 | (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n") |
| 2777 | (set (make-local-variable 'outline-level) |
| 2778 | #'(lambda () |
| 2779 | "`outline-level' function for Python mode." |
| 2780 | (1+ (/ (current-indentation) python-indent-offset)))) |
| 2781 | |
| 2782 | (python-skeleton-add-menu-items) |
| 2783 | |
| 2784 | (when python-indent-guess-indent-offset |
| 2785 | (python-indent-guess-indent-offset))) |
| 2786 | |
| 2787 | |
| 2788 | (provide 'python) |
| 2789 | ;;; python.el ends here |