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