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