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