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