Commit | Line | Data |
---|---|---|
45c138ac FEG |
1 | ;;; python.el -- Python's flying circus support for Emacs |
2 | ||
3 | ;; Copyright (C) 2010 Free Software Foundation, Inc. | |
4 | ||
5 | ;; Author: Fabián E. Gallina <fabian@anue.biz> | |
6 | ;; Maintainer: FSF | |
7 | ;; Created: Jul 2010 | |
8 | ;; Keywords: languages | |
9 | ||
10 | ;; This file is NOT part of GNU Emacs. | |
11 | ||
12 | ;; python.el is free software: you can redistribute it and/or modify | |
13 | ;; it under the terms of the GNU General Public License as published by | |
14 | ;; the Free Software Foundation, either version 3 of the License, or | |
15 | ;; (at your option) any later version. | |
16 | ||
17 | ;; python.el is distributed in the hope that it will be useful, | |
18 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of | |
19 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
20 | ;; GNU General Public License for more details. | |
21 | ||
22 | ;; You should have received a copy of the GNU General Public License | |
23 | ;; along with python.el. If not, see <http://www.gnu.org/licenses/>. | |
24 | ||
25 | ;;; Commentary: | |
26 | ||
27 | ;; Major mode for editing Python files with some fontification and | |
28 | ;; indentation bits extracted from original Dave Love's python.el | |
29 | ;; found in GNU/Emacs. | |
30 | ||
31 | ;; While it probably has less features than Dave Love's python.el and | |
32 | ;; PSF's python-mode.el it provides the main stuff you'll need while | |
33 | ;; keeping it simple :) | |
34 | ||
35 | ;; Implements Syntax highlighting, Indentation, Movement, Shell | |
36 | ;; interaction, Shell completion, Pdb tracking, Symbol completion, | |
37 | ;; Eldoc. | |
38 | ||
39 | ;; Syntax highlighting: Fontification of code is provided and supports | |
40 | ;; python's triple quoted strings properly. | |
41 | ||
42 | ;; Indentation: Automatic indentation with indentation cycling is | |
43 | ;; provided, it allows you to navigate different available levels of | |
44 | ;; indentation by hitting <tab> several times. | |
45 | ||
46 | ;; Movement: `beginning-of-defun' and `end-of-defun' functions are | |
47 | ;; properly implemented. A `beginning-of-innermost-defun' is defined | |
48 | ;; to navigate nested defuns. | |
49 | ||
50 | ;; Shell interaction: is provided and allows you easily execute any | |
51 | ;; block of code of your current buffer in an inferior Python process. | |
52 | ||
53 | ;; Shell completion: hitting tab will try to complete the current | |
4e531f7a | 54 | ;; word. Shell completion is implemented in a manner that if you |
45c138ac FEG |
55 | ;; change the `python-shell-interpreter' to any other (for example |
56 | ;; IPython) it should be easy to integrate another way to calculate | |
4e531f7a | 57 | ;; completions. You just need to especify your custom |
45c138ac FEG |
58 | ;; `python-shell-completion-setup-code' and |
59 | ;; `python-shell-completion-strings-code' | |
60 | ||
61 | ;; Pdb tracking: when you execute a block of code that contains some | |
62 | ;; call to pdb (or ipdb) it will prompt the block of code and will | |
63 | ;; follow the execution of pdb marking the current line with an arrow. | |
64 | ||
4e531f7a | 65 | ;; Symbol completion: you can complete the symbol at point. It uses |
45c138ac FEG |
66 | ;; the shell completion in background so you should run |
67 | ;; `python-shell-send-buffer' from time to time to get better results. | |
68 | ||
69 | ;; Eldoc: returns documentation for object at point by using the | |
4e531f7a | 70 | ;; inferior python subprocess to inspect its documentation. As you |
45c138ac FEG |
71 | ;; might guessed you should run `python-shell-send-buffer' from time |
72 | ;; to time to get better results too. | |
73 | ||
74 | ;;; Installation: | |
75 | ||
76 | ;; Add this to your .emacs: | |
77 | ||
78 | ;; (add-to-list 'load-path "/folder/containing/file") | |
79 | ;; (require 'python) | |
80 | ||
81 | ;;; TODO: | |
82 | ||
83 | ;; Ordered by priority: | |
84 | ||
85 | ;; Better decorator support for beginning of defun | |
86 | ||
db1497be | 87 | ;; Review code and cleanup |
45c138ac | 88 | |
db1497be | 89 | ;; (Perhaps) python-check |
45c138ac | 90 | |
db1497be FEG |
91 | ;; (Perhaps) ffap support |
92 | ||
93 | ;; (Perhaps) some skeletons (I never use them because of yasnippet) | |
45c138ac FEG |
94 | |
95 | ;;; Code: | |
96 | ||
97 | (require 'comint) | |
98 | (require 'ansi-color) | |
99 | (require 'outline) | |
100 | ||
101 | (eval-when-compile | |
102 | (require 'cl)) | |
103 | ||
104 | (autoload 'comint-mode "comint") | |
105 | ||
106 | ;;;###autoload | |
107 | (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode)) | |
108 | ;;;###autoload | |
109 | (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode)) | |
110 | ||
111 | (defgroup python nil | |
112 | "Python Language's flying circus support for Emacs." | |
113 | :group 'languages | |
114 | :version "23.2" | |
115 | :link '(emacs-commentary-link "python")) | |
116 | ||
117 | \f | |
118 | ;;; Bindings | |
119 | ||
120 | (defvar python-mode-map | |
121 | (let ((map (make-sparse-keymap))) | |
122 | ;; Indent specific | |
123 | (define-key map "\177" 'python-indent-dedent-line-backspace) | |
124 | (define-key map (kbd "<backtab>") 'python-indent-dedent-line) | |
125 | (define-key map "\C-c<" 'python-indent-shift-left) | |
126 | (define-key map "\C-c>" 'python-indent-shift-right) | |
127 | ;; Shell interaction | |
128 | (define-key map "\C-c\C-s" 'python-shell-send-string) | |
129 | (define-key map "\C-c\C-r" 'python-shell-send-region) | |
130 | (define-key map "\C-\M-x" 'python-shell-send-defun) | |
131 | (define-key map "\C-c\C-c" 'python-shell-send-buffer) | |
132 | (define-key map "\C-c\C-l" 'python-shell-send-file) | |
133 | (define-key map "\C-c\C-z" 'python-shell-switch-to-shell) | |
134 | ;; Utilities | |
135 | (substitute-key-definition 'complete-symbol 'completion-at-point | |
136 | map global-map) | |
137 | (easy-menu-define python-menu map "Python Mode menu" | |
138 | `("Python" | |
139 | :help "Python-specific Features" | |
140 | ["Shift region left" python-indent-shift-left :active mark-active | |
141 | :help "Shift region left by a single indentation step"] | |
142 | ["Shift region right" python-indent-shift-right :active mark-active | |
143 | :help "Shift region right by a single indentation step"] | |
144 | "-" | |
145 | ["Mark def/class" mark-defun | |
146 | :help "Mark outermost definition around point"] | |
147 | "-" | |
148 | ["Start of def/class" beginning-of-defun | |
149 | :help "Go to start of outermost definition around point"] | |
150 | ["Start of def/class" python-beginning-of-innermost-defun | |
151 | :help "Go to start of innermost definition around point"] | |
152 | ["End of def/class" end-of-defun | |
153 | :help "Go to end of definition around point"] | |
154 | "-" | |
155 | ["Start interpreter" run-python | |
156 | :help "Run inferior Python process in a separate buffer"] | |
157 | ["Switch to shell" python-shell-switch-to-shell | |
158 | :help "Switch to running inferior Python process"] | |
159 | ["Eval string" python-shell-send-string | |
160 | :help "Eval string in inferior Python session"] | |
161 | ["Eval buffer" python-shell-send-buffer | |
162 | :help "Eval buffer in inferior Python session"] | |
163 | ["Eval region" python-shell-send-region | |
164 | :help "Eval region in inferior Python session"] | |
165 | ["Eval defun" python-shell-send-defun | |
166 | :help "Eval defun in inferior Python session"] | |
167 | ["Eval file" python-shell-send-file | |
168 | :help "Eval file in inferior Python session"] | |
169 | ["Debugger" pdb :help "Run pdb under GUD"] | |
170 | "-" | |
171 | ["Complete symbol" completion-at-point | |
172 | :help "Complete symbol before point"])) | |
173 | map) | |
174 | "Keymap for `python-mode'.") | |
175 | ||
176 | \f | |
177 | ;;; Python specialized rx | |
178 | ||
179 | (defconst python-rx-constituents | |
180 | (list | |
181 | `(block-start . ,(rx symbol-start | |
182 | (or "def" "class" "if" "elif" "else" "try" | |
183 | "except" "finally" "for" "while" "with") | |
184 | symbol-end)) | |
185 | `(defun . ,(rx symbol-start (or "def" "class") symbol-end)) | |
186 | `(open-paren . ,(rx (or "{" "[" "("))) | |
187 | `(close-paren . ,(rx (or "}" "]" ")"))) | |
188 | `(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))) | |
189 | `(not-simple-operator . ,(rx (not (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))) | |
190 | `(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">" | |
191 | "=" "%" "**" "//" "<<" ">>" "<=" "!=" | |
192 | "==" ">=" "is" "not"))) | |
193 | `(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**=" | |
194 | ">>=" "<<=" "&=" "^=" "|="))))) | |
195 | ||
196 | (defmacro python-rx (&rest regexps) | |
4e531f7a | 197 | "Python mode especialized rx macro which supports common python named REGEXPS." |
45c138ac FEG |
198 | (let ((rx-constituents (append python-rx-constituents rx-constituents))) |
199 | (cond ((null regexps) | |
200 | (error "No regexp")) | |
201 | ((cdr regexps) | |
202 | (rx-to-string `(and ,@regexps) t)) | |
203 | (t | |
204 | (rx-to-string (car regexps) t))))) | |
205 | ||
206 | \f | |
207 | ;;; Font-lock and syntax | |
208 | ||
209 | (defvar python-font-lock-keywords | |
210 | ;; Keywords | |
211 | `(,(rx symbol-start | |
212 | (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with" | |
213 | "assert" "else" "if" "pass" "yield" "break" "except" "import" | |
214 | "print" "class" "exec" "in" "raise" "continue" "finally" "is" | |
215 | "return" "def" "for" "lambda" "try" "self") | |
216 | symbol-end) | |
217 | ;; functions | |
218 | (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_)))) | |
219 | (1 font-lock-function-name-face)) | |
220 | ;; classes | |
221 | (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_)))) | |
222 | (1 font-lock-type-face)) | |
223 | ;; Constants | |
224 | (,(rx symbol-start (group "None" symbol-end)) | |
225 | (1 font-lock-constant-face)) | |
226 | ;; Decorators. | |
227 | (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_)) | |
228 | (0+ "." (1+ (or word ?_))))) | |
229 | (1 font-lock-type-face)) | |
230 | ;; Builtin Exceptions | |
231 | (,(rx symbol-start | |
232 | (or "ArithmeticError" "AssertionError" "AttributeError" | |
233 | "BaseException" "BufferError" "BytesWarning" "DeprecationWarning" | |
234 | "EOFError" "EnvironmentError" "Exception" "FloatingPointError" | |
235 | "FutureWarning" "GeneratorExit" "IOError" "ImportError" | |
236 | "ImportWarning" "IndentationError" "IndexError" "KeyError" | |
237 | "KeyboardInterrupt" "LookupError" "MemoryError" "NameError" | |
238 | "NotImplemented" "NotImplementedError" "OSError" "OverflowError" | |
239 | "PendingDeprecationWarning" "ReferenceError" "RuntimeError" | |
240 | "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError" | |
241 | "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError" | |
242 | "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError" | |
243 | "UnicodeError" "UnicodeTranslateError" "UnicodeWarning" | |
244 | "UserWarning" "ValueError" "Warning" "ZeroDivisionError") | |
245 | symbol-end) . font-lock-type-face) | |
246 | ;; Builtins | |
247 | (,(rx (or line-start (not (any ". \t"))) (* (any " \t")) symbol-start | |
248 | (group | |
249 | (or "_" "__debug__" "__doc__" "__import__" "__name__" "__package__" | |
250 | "abs" "all" "any" "apply" "basestring" "bin" "bool" "buffer" | |
251 | "bytearray" "bytes" "callable" "chr" "classmethod" "cmp" "coerce" | |
252 | "compile" "complex" "copyright" "credits" "delattr" "dict" "dir" | |
253 | "divmod" "enumerate" "eval" "execfile" "exit" "file" "filter" | |
254 | "float" "format" "frozenset" "getattr" "globals" "hasattr" "hash" | |
255 | "help" "hex" "id" "input" "int" "intern" "isinstance" "issubclass" | |
256 | "iter" "len" "license" "list" "locals" "long" "map" "max" "min" | |
257 | "next" "object" "oct" "open" "ord" "pow" "print" "property" "quit" | |
258 | "range" "raw_input" "reduce" "reload" "repr" "reversed" "round" | |
259 | "set" "setattr" "slice" "sorted" "staticmethod" "str" "sum" | |
260 | "super" "tuple" "type" "unichr" "unicode" "vars" "xrange" "zip" | |
261 | "True" "False" "Ellipsis")) symbol-end) | |
262 | (1 font-lock-builtin-face)) | |
263 | ;; asignations | |
264 | ;; support for a = b = c = 5 | |
265 | (,(lambda (limit) | |
266 | (let ((re (python-rx (group (+ (any word ?. ?_))) (* space) | |
267 | assignment-operator))) | |
268 | (when (re-search-forward re limit t) | |
269 | (while (and (not (equal (nth 0 (syntax-ppss)) 0)) | |
270 | (re-search-forward re limit t))) | |
271 | (if (equal (nth 0 (syntax-ppss)) 0) | |
272 | t | |
273 | (set-match-data nil))))) | |
274 | (1 font-lock-variable-name-face nil nil)) | |
275 | ;; support for a, b, c = (1, 2, 3) | |
276 | (,(lambda (limit) | |
277 | (let ((re (python-rx (group (+ (any word ?. ?_))) (* space) | |
278 | (* ?, (* space) (+ (any word ?. ?_)) (* space)) | |
279 | ?, (* space) (+ (any word ?. ?_)) (* space) | |
280 | assignment-operator))) | |
281 | (when (and (re-search-forward re limit t) | |
282 | (goto-char (nth 3 (match-data)))) | |
283 | (while (and (not (equal (nth 0 (syntax-ppss)) 0)) | |
284 | (re-search-forward re limit t)) | |
285 | (goto-char (nth 3 (match-data)))) | |
286 | (if (equal (nth 0 (syntax-ppss)) 0) | |
287 | t | |
288 | (set-match-data nil))))) | |
289 | (1 font-lock-variable-name-face nil nil)))) | |
290 | ||
291 | ;; Fixme: Is there a better way? | |
292 | (defconst python-font-lock-syntactic-keywords | |
293 | ;; First avoid a sequence preceded by an odd number of backslashes. | |
294 | `((,(rx (not (any ?\\)) | |
295 | ?\\ (* (and ?\\ ?\\)) | |
296 | (group (syntax string-quote)) | |
297 | (backref 1) | |
298 | (group (backref 1))) | |
299 | (2 ,(string-to-syntax "\""))) ; dummy | |
300 | (,(rx (group (optional (any "uUrR"))) ; prefix gets syntax property | |
301 | (optional (any "rR")) ; possible second prefix | |
302 | (group (syntax string-quote)) ; maybe gets property | |
303 | (backref 2) ; per first quote | |
304 | (group (backref 2))) ; maybe gets property | |
305 | (1 (python-quote-syntax 1)) | |
306 | (2 (python-quote-syntax 2)) | |
307 | (3 (python-quote-syntax 3)))) | |
308 | "Make outer chars of triple-quote strings into generic string delimiters.") | |
309 | ||
310 | (defun python-quote-syntax (n) | |
311 | "Put `syntax-table' property correctly on triple quote. | |
312 | Used for syntactic keywords. N is the match number (1, 2 or 3)." | |
313 | ;; Given a triple quote, we have to check the context to know | |
314 | ;; whether this is an opening or closing triple or whether it's | |
315 | ;; quoted anyhow, and should be ignored. (For that we need to do | |
316 | ;; the same job as `syntax-ppss' to be correct and it seems to be OK | |
317 | ;; to use it here despite initial worries.) We also have to sort | |
318 | ;; out a possible prefix -- well, we don't _have_ to, but I think it | |
319 | ;; should be treated as part of the string. | |
320 | ||
321 | ;; Test cases: | |
322 | ;; ur"""ar""" x='"' # """ | |
323 | ;; x = ''' """ ' a | |
324 | ;; ''' | |
325 | ;; x '"""' x """ \"""" x | |
326 | (save-excursion | |
327 | (goto-char (match-beginning 0)) | |
328 | (cond | |
329 | ;; Consider property for the last char if in a fenced string. | |
330 | ((= n 3) | |
331 | (let* ((font-lock-syntactic-keywords nil) | |
332 | (syntax (syntax-ppss))) | |
333 | (when (eq t (nth 3 syntax)) ; after unclosed fence | |
334 | (goto-char (nth 8 syntax)) ; fence position | |
335 | (skip-chars-forward "uUrR") ; skip any prefix | |
336 | ;; Is it a matching sequence? | |
337 | (if (eq (char-after) (char-after (match-beginning 2))) | |
338 | (eval-when-compile (string-to-syntax "|")))))) | |
339 | ;; Consider property for initial char, accounting for prefixes. | |
340 | ((or (and (= n 2) ; leading quote (not prefix) | |
341 | (= (match-beginning 1) (match-end 1))) ; prefix is null | |
342 | (and (= n 1) ; prefix | |
343 | (/= (match-beginning 1) (match-end 1)))) ; non-empty | |
344 | (let ((font-lock-syntactic-keywords nil)) | |
345 | (unless (eq 'string (syntax-ppss-context (syntax-ppss))) | |
346 | (eval-when-compile (string-to-syntax "|"))))) | |
347 | ;; Otherwise (we're in a non-matching string) the property is | |
348 | ;; nil, which is OK. | |
349 | ))) | |
350 | ||
351 | (defvar python-mode-syntax-table | |
352 | (let ((table (make-syntax-table))) | |
353 | ;; Give punctuation syntax to ASCII that normally has symbol | |
354 | ;; syntax or has word syntax and isn't a letter. | |
355 | (let ((symbol (string-to-syntax "_")) | |
356 | (sst (standard-syntax-table))) | |
357 | (dotimes (i 128) | |
358 | (unless (= i ?_) | |
359 | (if (equal symbol (aref sst i)) | |
360 | (modify-syntax-entry i "." table))))) | |
361 | (modify-syntax-entry ?$ "." table) | |
362 | (modify-syntax-entry ?% "." table) | |
363 | ;; exceptions | |
364 | (modify-syntax-entry ?# "<" table) | |
365 | (modify-syntax-entry ?\n ">" table) | |
366 | (modify-syntax-entry ?' "\"" table) | |
367 | (modify-syntax-entry ?` "$" table) | |
368 | table) | |
369 | "Syntax table for Python files.") | |
370 | ||
371 | (defvar python-dotty-syntax-table | |
372 | (let ((table (make-syntax-table python-mode-syntax-table))) | |
373 | (modify-syntax-entry ?. "w" table) | |
374 | (modify-syntax-entry ?_ "w" table) | |
375 | table) | |
376 | "Dotty syntax table for Python files. | |
377 | It makes underscores and dots word constituent chars.") | |
378 | ||
379 | \f | |
380 | ;;; Indentation | |
381 | ||
382 | (defcustom python-indent-offset 4 | |
383 | "Default indentation offset for Python." | |
384 | :group 'python | |
385 | :type 'integer | |
386 | :safe 'integerp) | |
387 | ||
388 | (defcustom python-indent-guess-indent-offset t | |
389 | "Non-nil tells Python mode to guess `python-indent-offset' value." | |
390 | :type 'boolean | |
391 | :group 'python) | |
392 | ||
393 | (defvar python-indent-current-level 0 | |
394 | "Current indentation level `python-indent-line-function' is using.") | |
395 | ||
396 | (defvar python-indent-levels '(0) | |
397 | "Levels of indentation available for `python-indent-line-function'.") | |
398 | ||
399 | (defvar python-indent-dedenters '("else" "elif" "except" "finally") | |
400 | "List of words that should be dedented. | |
401 | These make `python-indent-calculate-indentation' subtract the value of | |
402 | `python-indent-offset'.") | |
403 | ||
404 | (defun python-indent-guess-indent-offset () | |
954aa7bd | 405 | "Guess and set `python-indent-offset' for the current buffer." |
bbac1eb8 FEG |
406 | (save-excursion |
407 | (save-restriction | |
408 | (widen) | |
409 | (goto-char (point-min)) | |
410 | (let ((found-block)) | |
411 | (while (and (not found-block) | |
412 | (re-search-forward | |
413 | (python-rx line-start block-start) nil t)) | |
414 | (when (and (not (syntax-ppss-context (syntax-ppss))) | |
415 | (progn | |
416 | (goto-char (line-end-position)) | |
417 | (forward-comment -1) | |
418 | (eq ?: (char-before)))) | |
419 | (setq found-block t))) | |
420 | (if (not found-block) | |
421 | (message "Can't guess python-indent-offset, using defaults: %s" | |
422 | python-indent-offset) | |
423 | (while (and (progn | |
424 | (goto-char (line-end-position)) | |
425 | (python-info-continuation-line-p)) | |
426 | (not (eobp))) | |
427 | (forward-line 1)) | |
428 | (forward-line 1) | |
429 | (forward-comment 1) | |
430 | (setq python-indent-offset (current-indentation))))))) | |
45c138ac FEG |
431 | |
432 | (defun python-indent-context (&optional stop) | |
433 | "Return information on indentation context. | |
434 | Optional argument STOP serves to stop recursive calls. | |
435 | ||
436 | Returns a cons with the form: | |
437 | ||
438 | \(STATUS . START) | |
439 | ||
440 | Where status can be any of the following symbols: | |
441 | ||
442 | * inside-paren: If point in between (), {} or [] | |
443 | * inside-string: If point is inside a string | |
444 | * after-backslash: Previous line ends in a backslash | |
445 | * after-beginning-of-block: Point is after beginning of block | |
446 | * after-line: Point is after normal line | |
447 | * no-indent: Point is at beginning of buffer or other special case | |
448 | ||
449 | START is the buffer position where the sexp starts." | |
450 | (save-restriction | |
451 | (widen) | |
452 | (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss))) | |
453 | (start)) | |
454 | (cons | |
455 | (cond | |
69bab1de | 456 | ;; Beginning of buffer |
19b122e4 FEG |
457 | ((save-excursion |
458 | (goto-char (line-beginning-position)) | |
459 | (bobp)) | |
69bab1de | 460 | 'no-indent) |
45c138ac FEG |
461 | ;; Inside a paren |
462 | ((setq start (nth 1 ppss)) | |
463 | 'inside-paren) | |
464 | ;; Inside string | |
465 | ((setq start (when (and (nth 3 ppss)) | |
466 | (nth 8 ppss))) | |
467 | 'inside-string) | |
468 | ;; After backslash | |
469 | ((setq start (when (not (syntax-ppss-context ppss)) | |
470 | (let ((line-beg-pos (line-beginning-position))) | |
471 | (when (eq ?\\ (char-before (1- line-beg-pos))) | |
472 | (- line-beg-pos 2))))) | |
473 | 'after-backslash) | |
474 | ;; After beginning of block | |
475 | ((setq start (save-excursion | |
476 | (let ((block-regexp (python-rx block-start)) | |
477 | (block-start-line-end ":[[:space:]]*$")) | |
478 | (back-to-indentation) | |
479 | (while (and (forward-comment -1) (not (bobp)))) | |
480 | (back-to-indentation) | |
481 | (when (or (python-info-continuation-line-p) | |
482 | (and (not (looking-at block-regexp)) | |
483 | (save-excursion | |
484 | (re-search-forward | |
485 | block-start-line-end | |
486 | (line-end-position) t)))) | |
487 | (while (and (forward-line -1) | |
488 | (python-info-continuation-line-p) | |
489 | (not (bobp)))) | |
490 | (when (not (looking-at block-regexp)) | |
491 | (forward-line 1))) | |
492 | (back-to-indentation) | |
493 | (when (and (looking-at block-regexp) | |
494 | (or (re-search-forward | |
495 | block-start-line-end | |
496 | (line-end-position) t) | |
497 | (python-info-continuation-line-p))) | |
498 | (point-marker))))) | |
499 | 'after-beginning-of-block) | |
500 | ;; After normal line | |
501 | ((setq start (save-excursion | |
502 | (while (and (forward-comment -1) (not (bobp)))) | |
503 | (while (and (not (back-to-indentation)) | |
504 | (not (bobp)) | |
505 | (if (> (nth 0 (syntax-ppss)) 0) | |
506 | (forward-line -1) | |
507 | (if (save-excursion | |
508 | (forward-line -1) | |
509 | (python-info-line-ends-backslash-p)) | |
510 | (forward-line -1))))) | |
511 | (point-marker))) | |
512 | 'after-line) | |
513 | ;; Do not indent | |
514 | (t 'no-indent)) | |
515 | start)))) | |
516 | ||
517 | (defun python-indent-calculate-indentation () | |
518 | "Calculate correct indentation offset for the current line." | |
519 | (let* ((indentation-context (python-indent-context)) | |
520 | (context-status (car indentation-context)) | |
521 | (context-start (cdr indentation-context))) | |
522 | (save-restriction | |
523 | (widen) | |
524 | (save-excursion | |
525 | (case context-status | |
526 | ('no-indent 0) | |
527 | ('after-beginning-of-block | |
528 | (goto-char context-start) | |
529 | (+ (current-indentation) python-indent-offset)) | |
530 | ('after-line | |
531 | (- | |
532 | (save-excursion | |
533 | (goto-char context-start) | |
534 | (current-indentation)) | |
535 | (if (progn | |
536 | (back-to-indentation) | |
537 | (looking-at (regexp-opt python-indent-dedenters))) | |
538 | python-indent-offset | |
539 | 0))) | |
540 | ('inside-string | |
541 | (goto-char context-start) | |
542 | (current-indentation)) | |
543 | ('after-backslash | |
544 | (let* ((block-continuation | |
545 | (save-excursion | |
546 | (forward-line -1) | |
547 | (python-info-block-continuation-line-p))) | |
548 | (assignment-continuation | |
549 | (save-excursion | |
550 | (forward-line -1) | |
551 | (python-info-assignment-continuation-line-p))) | |
552 | (indentation (cond (block-continuation | |
553 | (goto-char block-continuation) | |
554 | (re-search-forward | |
555 | (python-rx block-start (* space)) | |
556 | (line-end-position) t) | |
557 | (current-column)) | |
558 | (assignment-continuation | |
559 | (goto-char assignment-continuation) | |
560 | (re-search-forward | |
561 | (python-rx simple-operator) | |
562 | (line-end-position) t) | |
563 | (forward-char 1) | |
564 | (re-search-forward | |
565 | (python-rx (* space)) | |
566 | (line-end-position) t) | |
567 | (current-column)) | |
568 | (t | |
569 | (goto-char context-start) | |
570 | (current-indentation))))) | |
571 | indentation)) | |
572 | ('inside-paren | |
573 | (- | |
574 | (save-excursion | |
575 | (goto-char context-start) | |
576 | (forward-char) | |
13d1a42e FEG |
577 | (save-restriction |
578 | (narrow-to-region | |
579 | (line-beginning-position) | |
580 | (line-end-position)) | |
581 | (forward-comment 1)) | |
582 | (if (looking-at "$") | |
45c138ac FEG |
583 | (+ (current-indentation) python-indent-offset) |
584 | (forward-comment 1) | |
585 | (current-column))) | |
586 | (if (progn | |
587 | (back-to-indentation) | |
588 | (looking-at (regexp-opt '(")" "]" "}")))) | |
589 | python-indent-offset | |
590 | 0)))))))) | |
591 | ||
592 | (defun python-indent-calculate-levels () | |
593 | "Calculate `python-indent-levels' and reset `python-indent-current-level'." | |
594 | (let* ((indentation (python-indent-calculate-indentation)) | |
595 | (remainder (% indentation python-indent-offset)) | |
596 | (steps (/ (- indentation remainder) python-indent-offset))) | |
597 | (setq python-indent-levels '()) | |
598 | (setq python-indent-levels (cons 0 python-indent-levels)) | |
599 | (dotimes (step steps) | |
600 | (setq python-indent-levels | |
601 | (cons (* python-indent-offset (1+ step)) python-indent-levels))) | |
602 | (when (not (eq 0 remainder)) | |
603 | (setq python-indent-levels | |
604 | (cons (+ (* python-indent-offset steps) remainder) | |
605 | python-indent-levels))) | |
606 | (setq python-indent-levels (nreverse python-indent-levels)) | |
607 | (setq python-indent-current-level (1- (length python-indent-levels))))) | |
608 | ||
609 | (defun python-indent-toggle-levels () | |
610 | "Toggle `python-indent-current-level' over `python-indent-levels'." | |
611 | (setq python-indent-current-level (1- python-indent-current-level)) | |
612 | (when (< python-indent-current-level 0) | |
613 | (setq python-indent-current-level (1- (length python-indent-levels))))) | |
614 | ||
615 | (defun python-indent-line (&optional force-toggle) | |
616 | "Internal implementation of `python-indent-line-function'. | |
617 | ||
618 | Uses the offset calculated in | |
619 | `python-indent-calculate-indentation' and available levels | |
620 | indicated by the variable `python-indent-levels'. | |
621 | ||
622 | When the variable `last-command' is equal to | |
623 | `indent-for-tab-command' or FORCE-TOGGLE is non-nil: | |
624 | ||
625 | * Cycles levels indicated in the variable `python-indent-levels' | |
626 | by setting the current level in the variable | |
627 | `python-indent-current-level'. | |
628 | ||
629 | When the variable `last-command' is not equal to | |
630 | `indent-for-tab-command' and FORCE-TOGGLE is nil: | |
631 | ||
632 | * calculates possible indentation levels and saves it in the | |
633 | variable `python-indent-levels'. | |
634 | ||
635 | * sets the variable `python-indent-current-level' correctly so | |
636 | offset is equal to (`nth' `python-indent-current-level' | |
637 | `python-indent-levels')" | |
638 | (if (or (and (eq this-command 'indent-for-tab-command) | |
639 | (eq last-command this-command)) | |
640 | force-toggle) | |
641 | (python-indent-toggle-levels) | |
642 | (python-indent-calculate-levels)) | |
643 | (beginning-of-line) | |
644 | (delete-horizontal-space) | |
645 | (indent-to (nth python-indent-current-level python-indent-levels)) | |
646 | (save-restriction | |
647 | (widen) | |
648 | (let ((closing-block-point (python-info-closing-block))) | |
649 | (when closing-block-point | |
650 | (message "Closes %s" (buffer-substring | |
651 | closing-block-point | |
652 | (save-excursion | |
653 | (goto-char closing-block-point) | |
654 | (line-end-position)))))))) | |
655 | ||
656 | (defun python-indent-line-function () | |
657 | "`indent-line-function' for Python mode. | |
658 | Internally just calls `python-indent-line'." | |
659 | (python-indent-line)) | |
660 | ||
661 | (defun python-indent-dedent-line () | |
662 | "Dedent current line." | |
663 | (interactive "*") | |
664 | (when (and (not (syntax-ppss-context (syntax-ppss))) | |
665 | (<= (point-marker) (save-excursion | |
666 | (back-to-indentation) | |
667 | (point-marker))) | |
668 | (> (current-column) 0)) | |
669 | (python-indent-line t) | |
670 | t)) | |
671 | ||
672 | (defun python-indent-dedent-line-backspace (arg) | |
673 | "Dedent current line. | |
674 | Argument ARG is passed to `backward-delete-char-untabify' when | |
675 | point is not in between the indentation." | |
676 | (interactive "*p") | |
677 | (when (not (python-indent-dedent-line)) | |
678 | (backward-delete-char-untabify arg))) | |
183f9296 | 679 | (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede) |
45c138ac FEG |
680 | |
681 | (defun python-indent-region (start end) | |
682 | "Indent a python region automagically. | |
683 | ||
684 | Called from a program, START and END specify the region to indent." | |
685 | (save-excursion | |
686 | (goto-char end) | |
687 | (setq end (point-marker)) | |
688 | (goto-char start) | |
689 | (or (bolp) (forward-line 1)) | |
690 | (while (< (point) end) | |
691 | (or (and (bolp) (eolp)) | |
692 | (let (word) | |
693 | (forward-line -1) | |
694 | (back-to-indentation) | |
695 | (setq word (current-word)) | |
696 | (forward-line 1) | |
697 | (when word | |
698 | (beginning-of-line) | |
699 | (delete-horizontal-space) | |
700 | (indent-to (python-indent-calculate-indentation))))) | |
701 | (forward-line 1)) | |
702 | (move-marker end nil))) | |
703 | ||
704 | (defun python-indent-shift-left (start end &optional count) | |
705 | "Shift lines contained in region START END by COUNT columns to the left. | |
706 | ||
707 | COUNT defaults to `python-indent-offset'. | |
708 | ||
709 | If region isn't active, the current line is shifted. | |
710 | ||
711 | The shifted region includes the lines in which START and END lie. | |
712 | ||
713 | An error is signaled if any lines in the region are indented less | |
714 | than COUNT columns." | |
715 | (interactive | |
716 | (if mark-active | |
717 | (list (region-beginning) (region-end) current-prefix-arg) | |
718 | (list (line-beginning-position) (line-end-position) current-prefix-arg))) | |
719 | (if count | |
720 | (setq count (prefix-numeric-value count)) | |
721 | (setq count python-indent-offset)) | |
722 | (when (> count 0) | |
723 | (save-excursion | |
724 | (goto-char start) | |
725 | (while (< (point) end) | |
726 | (if (and (< (current-indentation) count) | |
727 | (not (looking-at "[ \t]*$"))) | |
728 | (error "Can't shift all lines enough")) | |
729 | (forward-line)) | |
730 | (indent-rigidly start end (- count))))) | |
731 | ||
732 | (add-to-list 'debug-ignored-errors "^Can't shift all lines enough") | |
733 | ||
734 | (defun python-indent-shift-right (start end &optional count) | |
735 | "Shift lines contained in region START END by COUNT columns to the left. | |
736 | ||
737 | COUNT defaults to `python-indent-offset'. | |
738 | ||
739 | If region isn't active, the current line is shifted. | |
740 | ||
741 | The shifted region includes the lines in which START and END | |
742 | lie." | |
743 | (interactive | |
744 | (if mark-active | |
745 | (list (region-beginning) (region-end) current-prefix-arg) | |
746 | (list (line-beginning-position) (line-end-position) current-prefix-arg))) | |
747 | (if count | |
748 | (setq count (prefix-numeric-value count)) | |
749 | (setq count python-indent-offset)) | |
750 | (indent-rigidly start end count)) | |
751 | ||
752 | \f | |
753 | ;;; Navigation | |
754 | ||
755 | (defvar python-beginning-of-defun-regexp | |
756 | "^\\(def\\|class\\)[[:space:]]+[[:word:]]+" | |
757 | "Regular expresion matching beginning of outermost class or function.") | |
758 | ||
759 | (defvar python-beginning-of-innermost-defun-regexp | |
760 | "^[[:space:]]*\\(def\\|class\\)[[:space:]]+[[:word:]]+" | |
761 | "Regular expresion matching beginning of innermost class or function.") | |
762 | ||
763 | (defun python-beginning-of-defun (&optional innermost) | |
764 | "Move point to the beginning of innermost/outermost def or class. | |
765 | If INNERMOST is non-nil then move to the beginning of the | |
766 | innermost definition." | |
767 | (let ((starting-point (point-marker)) | |
768 | (nonblank-line-indent) | |
769 | (defun-indent) | |
770 | (defun-point) | |
771 | (regexp (if innermost | |
772 | python-beginning-of-innermost-defun-regexp | |
773 | python-beginning-of-defun-regexp))) | |
774 | (back-to-indentation) | |
775 | (if (and (not (looking-at "@")) | |
776 | (not (looking-at regexp))) | |
777 | (forward-comment -1) | |
778 | (while (and (not (eobp)) | |
779 | (forward-line 1) | |
780 | (not (back-to-indentation)) | |
781 | (looking-at "@")))) | |
782 | (when (not (looking-at regexp)) | |
783 | (re-search-backward regexp nil t)) | |
784 | (setq nonblank-line-indent (+ (current-indentation) python-indent-offset)) | |
785 | (setq defun-indent (current-indentation)) | |
786 | (setq defun-point (point-marker)) | |
787 | (if (> nonblank-line-indent defun-indent) | |
788 | (progn | |
789 | (goto-char defun-point) | |
790 | (forward-line -1) | |
791 | (while (and (looking-at "@") | |
792 | (forward-line -1) | |
793 | (not (bobp)) | |
794 | (not (back-to-indentation)))) | |
df700cc9 FEG |
795 | (unless (bobp) |
796 | (forward-line 1)) | |
45c138ac FEG |
797 | (point-marker)) |
798 | (if innermost | |
799 | (python-beginning-of-defun) | |
800 | (goto-char starting-point) | |
801 | nil)))) | |
802 | ||
803 | (defun python-beginning-of-defun-function () | |
804 | "Move point to the beginning of outermost def or class. | |
805 | Returns nil if point is not in a def or class." | |
806 | (python-beginning-of-defun nil)) | |
807 | ||
808 | (defun python-beginning-of-innermost-defun () | |
809 | "Move point to the beginning of innermost def or class. | |
810 | Returns nil if point is not in a def or class." | |
811 | (interactive) | |
812 | (python-beginning-of-defun t)) | |
813 | ||
814 | (defun python-end-of-defun-function () | |
815 | "Move point to the end of def or class. | |
816 | Returns nil if point is not in a def or class." | |
817 | (let ((starting-point (point-marker)) | |
818 | (defun-regexp (python-rx defun)) | |
819 | (beg-defun-indent)) | |
820 | (back-to-indentation) | |
821 | (if (looking-at "@") | |
822 | (while (and (not (eobp)) | |
823 | (forward-line 1) | |
824 | (not (back-to-indentation)) | |
825 | (looking-at "@"))) | |
826 | (while (and (not (bobp)) | |
827 | (not (progn (back-to-indentation) (current-word))) | |
828 | (forward-line -1)))) | |
829 | (when (or (not (equal (current-indentation) 0)) | |
830 | (string-match defun-regexp (current-word))) | |
831 | (setq beg-defun-indent (save-excursion | |
832 | (or (looking-at defun-regexp) | |
833 | (python-beginning-of-innermost-defun)) | |
834 | (current-indentation))) | |
835 | (while (and (forward-line 1) | |
836 | (not (eobp)) | |
837 | (or (not (current-word)) | |
838 | (> (current-indentation) beg-defun-indent)))) | |
839 | (while (and (forward-comment -1) | |
840 | (not (bobp)))) | |
841 | (forward-line 1) | |
842 | (point-marker)))) | |
843 | ||
844 | \f | |
845 | ;;; Shell integration | |
846 | ||
847 | (defvar python-shell-buffer-name "Python" | |
848 | "Default buffer name for Python interpreter.") | |
849 | ||
850 | (defcustom python-shell-interpreter "python" | |
851 | "Default Python interpreter for shell." | |
852 | :group 'python | |
853 | :type 'string | |
854 | :safe 'stringp) | |
855 | ||
856 | (defcustom python-shell-interpreter-args "-i" | |
857 | "Default arguments for the Python interpreter." | |
858 | :group 'python | |
859 | :type 'string | |
860 | :safe 'stringp) | |
861 | ||
862 | (defcustom python-shell-prompt-regexp ">>> " | |
863 | "Regex matching top\-level input prompt of python shell. | |
864 | The regex should not contain a caret (^) at the beginning." | |
865 | :type 'string | |
866 | :group 'python | |
867 | :safe 'stringp) | |
868 | ||
869 | (defcustom python-shell-prompt-block-regexp "[.][.][.] " | |
870 | "Regex matching block input prompt of python shell. | |
871 | The regex should not contain a caret (^) at the beginning." | |
872 | :type 'string | |
873 | :group 'python | |
874 | :safe 'stringp) | |
875 | ||
876 | (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ " | |
877 | "Regex matching pdb input prompt of python shell. | |
878 | The regex should not contain a caret (^) at the beginning." | |
879 | :type 'string | |
880 | :group 'python | |
881 | :safe 'stringp) | |
882 | ||
883 | (defcustom python-shell-compilation-regexp-alist | |
884 | `((,(rx line-start (1+ (any " \t")) "File \"" | |
885 | (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c | |
886 | "\", line " (group (1+ digit))) | |
887 | 1 2) | |
888 | (,(rx " in file " (group (1+ not-newline)) " on line " | |
889 | (group (1+ digit))) | |
890 | 1 2) | |
891 | (,(rx line-start "> " (group (1+ (not (any "(\"<")))) | |
892 | "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()") | |
893 | 1 2)) | |
894 | "`compilation-error-regexp-alist' for inferior Python." | |
895 | :type '(alist string) | |
896 | :group 'python) | |
897 | ||
898 | (defun python-shell-get-process-name (dedicated) | |
899 | "Calculate the appropiate process name for inferior Python process. | |
900 | ||
901 | If DEDICATED is t and the variable `buffer-file-name' is non-nil | |
902 | returns a string with the form | |
903 | `python-shell-buffer-name'[variable `buffer-file-name'] else | |
904 | returns the value of `python-shell-buffer-name'. | |
905 | ||
906 | After calculating the process name add the buffer name for the | |
907 | process in the `same-window-buffer-names' list" | |
908 | (let ((process-name | |
909 | (if (and dedicated | |
910 | buffer-file-name) | |
911 | (format "%s[%s]" python-shell-buffer-name buffer-file-name) | |
912 | (format "%s" python-shell-buffer-name)))) | |
913 | (add-to-list 'same-window-buffer-names (purecopy | |
914 | (format "*%s*" process-name))) | |
915 | process-name)) | |
916 | ||
917 | (defun python-shell-parse-command () | |
918 | "Calculates the string used to execute the inferior Python process." | |
919 | (format "%s %s" python-shell-interpreter python-shell-interpreter-args)) | |
920 | ||
921 | (defun python-comint-output-filter-function (output) | |
922 | "Hook run after content is put into comint buffer. | |
923 | OUTPUT is a string with the contents of the buffer." | |
924 | (ansi-color-filter-apply output)) | |
925 | ||
926 | (defvar inferior-python-mode-current-file nil | |
927 | "Current file from which a region was sent.") | |
928 | (make-variable-buffer-local 'inferior-python-mode-current-file) | |
929 | ||
930 | (defvar inferior-python-mode-current-temp-file nil | |
931 | "Current temp file sent to process.") | |
932 | (make-variable-buffer-local 'inferior-python-mode-current-file) | |
933 | ||
934 | (define-derived-mode inferior-python-mode comint-mode "Inferior Python" | |
935 | "Major mode for Python inferior process." | |
936 | (set-syntax-table python-mode-syntax-table) | |
937 | (setq mode-line-process '(":%s")) | |
938 | (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)" | |
939 | python-shell-prompt-regexp | |
940 | python-shell-prompt-block-regexp | |
941 | python-shell-prompt-pdb-regexp)) | |
942 | (make-local-variable 'comint-output-filter-functions) | |
943 | (add-hook 'comint-output-filter-functions | |
944 | 'python-comint-output-filter-function) | |
945 | (add-hook 'comint-output-filter-functions | |
946 | 'python-pdbtrack-comint-output-filter-function) | |
947 | (set (make-local-variable 'compilation-error-regexp-alist) | |
948 | python-shell-compilation-regexp-alist) | |
ed0eb594 FEG |
949 | (define-key inferior-python-mode-map [remap complete-symbol] |
950 | 'completion-at-point) | |
951 | (add-hook 'completion-at-point-functions | |
952 | 'python-shell-completion-complete-at-point nil 'local) | |
45c138ac FEG |
953 | (compilation-shell-minor-mode 1)) |
954 | ||
955 | (defun run-python (dedicated cmd) | |
956 | "Run an inferior Python process. | |
957 | ||
958 | Input and output via buffer *\\[python-shell-buffer-name]*. | |
959 | ||
960 | If there is a process already running in | |
961 | *\\[python-shell-buffer-name]*, switch to that buffer. | |
962 | ||
963 | With argument, allows you to: | |
964 | ||
965 | * Define DEDICATED so a dedicated process for the current buffer | |
966 | is open. | |
967 | ||
968 | * Define CMD so you can edit the command used to call the | |
969 | interpreter (default is value of `python-shell-interpreter' and | |
970 | arguments defined in `python-shell-interpreter-args'). | |
971 | ||
972 | Runs the hook `inferior-python-mode-hook' (after the | |
973 | `comint-mode-hook' is run). | |
974 | ||
975 | \(Type \\[describe-mode] in the process buffer for a list of | |
976 | commands.)" | |
977 | (interactive | |
978 | (if current-prefix-arg | |
979 | (list | |
980 | (y-or-n-p "Make dedicated process? ") | |
981 | (read-string "Run Python: " (python-shell-parse-command))) | |
982 | (list nil (python-shell-parse-command)))) | |
983 | (let* ((proc-name (python-shell-get-process-name dedicated)) | |
984 | (proc-buffer-name (format "*%s*" proc-name))) | |
985 | (when (not (comint-check-proc proc-buffer-name)) | |
986 | (let ((cmdlist (split-string-and-unquote cmd))) | |
987 | (set-buffer | |
988 | (apply 'make-comint proc-name (car cmdlist) nil | |
989 | (cdr cmdlist))) | |
990 | (inferior-python-mode))) | |
991 | (pop-to-buffer proc-buffer-name)) | |
992 | dedicated) | |
993 | ||
994 | (defun python-shell-get-process () | |
995 | "Get inferior Python process for current buffer and return it." | |
996 | (let* ((dedicated-proc-name (python-shell-get-process-name t)) | |
997 | (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name)) | |
998 | (global-proc-name (python-shell-get-process-name nil)) | |
999 | (global-proc-buffer-name (format "*%s*" global-proc-name)) | |
1000 | (dedicated-running (comint-check-proc dedicated-proc-buffer-name)) | |
1001 | (global-running (comint-check-proc global-proc-buffer-name))) | |
1002 | ;; Always prefer dedicated | |
1003 | (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name) | |
1004 | (and global-running global-proc-buffer-name))))) | |
1005 | ||
1006 | (defun python-shell-get-or-create-process () | |
1007 | "Get or create an inferior Python process for current buffer and return it." | |
79dafa51 FEG |
1008 | (let* ((old-buffer (current-buffer)) |
1009 | (dedicated-proc-name (python-shell-get-process-name t)) | |
45c138ac FEG |
1010 | (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name)) |
1011 | (global-proc-name (python-shell-get-process-name nil)) | |
1012 | (global-proc-buffer-name (format "*%s*" global-proc-name)) | |
1013 | (dedicated-running (comint-check-proc dedicated-proc-buffer-name)) | |
1014 | (global-running (comint-check-proc global-proc-buffer-name)) | |
1015 | (current-prefix-arg 4)) | |
1016 | (when (and (not dedicated-running) (not global-running)) | |
1017 | (if (call-interactively 'run-python) | |
1018 | (setq dedicated-running t) | |
1019 | (setq global-running t))) | |
1020 | ;; Always prefer dedicated | |
79dafa51 | 1021 | (switch-to-buffer old-buffer) |
45c138ac FEG |
1022 | (get-buffer-process (if dedicated-running |
1023 | dedicated-proc-buffer-name | |
1024 | global-proc-buffer-name)))) | |
1025 | ||
13d914ed | 1026 | (defun python-shell-send-string (string &optional process) |
45c138ac FEG |
1027 | "Send STRING to inferior Python process." |
1028 | (interactive "sPython command: ") | |
13d914ed | 1029 | (let ((process (or process (python-shell-get-or-create-process)))) |
fc87f759 | 1030 | (when (called-interactively-p 'interactive) |
13d914ed | 1031 | (message (format "Sent: %s..." string))) |
45c138ac FEG |
1032 | (comint-send-string process string) |
1033 | (when (or (not (string-match "\n$" string)) | |
1034 | (string-match "\n[ \t].*\n?$" string)) | |
1035 | (comint-send-string process "\n")))) | |
1036 | ||
1037 | (defun python-shell-send-region (start end) | |
1038 | "Send the region delimited by START and END to inferior Python process." | |
1039 | (interactive "r") | |
1040 | (let* ((contents (buffer-substring start end)) | |
1041 | (current-file (buffer-file-name)) | |
1042 | (process (python-shell-get-or-create-process)) | |
66b0b492 | 1043 | (temp-file (make-temp-file "py"))) |
45c138ac FEG |
1044 | (with-temp-file temp-file |
1045 | (insert contents) | |
1046 | (delete-trailing-whitespace) | |
1047 | (goto-char (point-min)) | |
1048 | (message (format "Sent: %s..." | |
1049 | (buffer-substring (point-min) | |
1050 | (line-end-position))))) | |
1051 | (with-current-buffer (process-buffer process) | |
1052 | (setq inferior-python-mode-current-file current-file) | |
66b0b492 FEG |
1053 | (setq inferior-python-mode-current-temp-file temp-file)) |
1054 | (python-shell-send-file temp-file process))) | |
45c138ac FEG |
1055 | |
1056 | (defun python-shell-send-buffer () | |
1057 | "Send the entire buffer to inferior Python process." | |
1058 | (interactive) | |
1059 | (save-restriction | |
1060 | (widen) | |
1061 | (python-shell-send-region (point-min) (point-max)))) | |
1062 | ||
1063 | (defun python-shell-send-defun (arg) | |
1064 | "Send the (inner|outer)most def or class to inferior Python process. | |
1065 | When argument ARG is non-nil sends the innermost defun." | |
1066 | (interactive "P") | |
1067 | (save-excursion | |
1068 | (python-shell-send-region (progn | |
1069 | (or (if arg | |
1070 | (python-beginning-of-innermost-defun) | |
1071 | (python-beginning-of-defun-function)) | |
1072 | (progn (beginning-of-line) (point-marker)))) | |
1073 | (progn | |
1074 | (or (python-end-of-defun-function) | |
1075 | (progn (end-of-line) (point-marker))))))) | |
1076 | ||
66b0b492 | 1077 | (defun python-shell-send-file (file-name &optional process) |
4e531f7a | 1078 | "Send FILE-NAME to inferior Python PROCESS." |
45c138ac | 1079 | (interactive "fFile to send: ") |
b962ebad FEG |
1080 | (let ((process (or process (python-shell-get-or-create-process))) |
1081 | (full-file-name (expand-file-name file-name))) | |
13d914ed | 1082 | (python-shell-send-string |
b962ebad | 1083 | (format |
13d914ed FEG |
1084 | "__pyfile = open('%s'); exec(compile(__pyfile.read(), '%s', 'exec')); __pyfile.close()" |
1085 | full-file-name full-file-name) | |
1086 | process))) | |
45c138ac FEG |
1087 | |
1088 | (defun python-shell-switch-to-shell () | |
1089 | "Switch to inferior Python process buffer." | |
1090 | (interactive) | |
1091 | (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t)) | |
1092 | ||
1093 | \f | |
1094 | ;;; Shell completion | |
1095 | ||
1096 | (defvar python-shell-completion-setup-code | |
1097 | "try: | |
1098 | import readline | |
1099 | except ImportError: | |
1100 | def __COMPLETER_all_completions(text): [] | |
1101 | else: | |
1102 | import rlcompleter | |
1103 | readline.set_completer(rlcompleter.Completer().complete) | |
1104 | def __COMPLETER_all_completions(text): | |
1105 | import sys | |
1106 | completions = [] | |
1107 | try: | |
1108 | i = 0 | |
1109 | while True: | |
1110 | res = readline.get_completer()(text, i) | |
1111 | if not res: break | |
1112 | i += 1 | |
1113 | completions.append(res) | |
1114 | except NameError: | |
1115 | pass | |
1116 | return completions" | |
1117 | "Code used to setup completion in inferior Python processes.") | |
1118 | ||
1119 | (defvar python-shell-completion-strings-code | |
1120 | "';'.join(__COMPLETER_all_completions('''%s'''))\n" | |
1121 | "Python code used to get a string of completions separated by semicolons.") | |
1122 | ||
1123 | (defun python-shell-completion-setup () | |
1124 | "Send `python-shell-completion-setup-code' to inferior Python process. | |
1125 | Also binds <tab> to `python-shell-complete-or-indent' in the | |
1126 | `inferior-python-mode-map' and adds | |
1127 | `python-shell-completion-complete-at-point' to the | |
1128 | `comint-dynamic-complete-functions' list. | |
1129 | It is specially designed to be added to the | |
1130 | `inferior-python-mode-hook'." | |
1131 | (when python-shell-completion-setup-code | |
1132 | (let ((temp-file (make-temp-file "py")) | |
1133 | (process (get-buffer-process (current-buffer)))) | |
1134 | (with-temp-file temp-file | |
1135 | (insert python-shell-completion-setup-code) | |
1136 | (delete-trailing-whitespace) | |
1137 | (goto-char (point-min))) | |
66b0b492 | 1138 | (python-shell-send-file temp-file process) |
45c138ac FEG |
1139 | (message (format "Completion setup code sent."))) |
1140 | (add-to-list (make-local-variable | |
1141 | 'comint-dynamic-complete-functions) | |
1142 | 'python-shell-completion-complete-at-point) | |
1143 | (define-key inferior-python-mode-map (kbd "<tab>") | |
1144 | 'python-shell-completion-complete-or-indent))) | |
1145 | ||
075a0f61 FEG |
1146 | (defun python-shell-completion--get-completions (input process) |
1147 | "Retrieve available completions for INPUT using PROCESS." | |
1148 | (with-current-buffer (process-buffer process) | |
1149 | (let ((completions)) | |
1150 | (python-shell-send-string | |
1151 | (format python-shell-completion-strings-code input) | |
1152 | process) | |
1153 | (accept-process-output process) | |
1154 | (when comint-last-output-start | |
1155 | (setq completions | |
1156 | (split-string | |
1157 | (buffer-substring-no-properties | |
1158 | comint-last-output-start | |
1159 | (save-excursion | |
1160 | (goto-char comint-last-output-start) | |
1161 | (line-end-position))) | |
1162 | ";\\|\"\\|'\\|(" t)) | |
1163 | (comint-delete-output) | |
1164 | completions)))) | |
1165 | ||
1166 | (defun python-shell-completion--get-completion (input completions) | |
1167 | "Get completion for INPUT using COMPLETIONS." | |
1168 | (let ((completion (when completions | |
1169 | (try-completion input completions)))) | |
1170 | (cond ((eq completion t) | |
1171 | input) | |
1172 | ((null completion) | |
1173 | (message "Can't find completion for \"%s\"" input) | |
1174 | (ding) | |
1175 | input) | |
1176 | ((not (string= input completion)) | |
1177 | completion) | |
1178 | (t | |
1179 | (message "Making completion list...") | |
1180 | (with-output-to-temp-buffer "*Python Completions*" | |
1181 | (display-completion-list | |
1182 | (all-completions input completions))) | |
1183 | input)))) | |
1184 | ||
45c138ac FEG |
1185 | (defun python-shell-completion-complete-at-point () |
1186 | "Perform completion at point in inferior Python process." | |
1187 | (interactive) | |
3d6913c7 FEG |
1188 | (with-syntax-table python-dotty-syntax-table |
1189 | (when (and comint-last-prompt-overlay | |
1190 | (> (point-marker) (overlay-end comint-last-prompt-overlay))) | |
1191 | (let* ((process (get-buffer-process (current-buffer))) | |
075a0f61 FEG |
1192 | (input (substring-no-properties |
1193 | (or (comint-word (current-word)) "") nil nil))) | |
1194 | (delete-char (- (length input))) | |
1195 | (insert | |
1196 | (python-shell-completion--get-completion | |
1197 | input (python-shell-completion--get-completions input process))))))) | |
45c138ac | 1198 | |
45c138ac FEG |
1199 | (defun python-shell-completion-complete-or-indent () |
1200 | "Complete or indent depending on the context. | |
1201 | If content before pointer is all whitespace indent. If not try to | |
1202 | complete." | |
1203 | (interactive) | |
1204 | (if (string-match "^[[:space:]]*$" | |
1205 | (buffer-substring (comint-line-beginning-position) | |
1206 | (point-marker))) | |
1207 | (indent-for-tab-command) | |
1208 | (comint-dynamic-complete))) | |
1209 | ||
1210 | (add-hook 'inferior-python-mode-hook | |
1211 | #'python-shell-completion-setup) | |
1212 | ||
1213 | \f | |
1214 | ;;; PDB Track integration | |
1215 | ||
1216 | (defvar python-pdbtrack-stacktrace-info-regexp | |
1217 | "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()" | |
1218 | "Regexp matching stacktrace information. | |
1219 | It is used to extract the current line and module beign | |
1220 | inspected. | |
1221 | The regexp should not start with a caret (^) and can contain a | |
1222 | string placeholder (\%s) which is replaced with the filename | |
1223 | beign inspected (so other files in the debugging process are not | |
1224 | opened)") | |
1225 | ||
1226 | (defvar python-pdbtrack-tracking-buffers '() | |
1227 | "Alist containing elements of form (#<buffer> . #<buffer>). | |
1228 | The car of each element of the alist is the tracking buffer and | |
1229 | the cdr is the tracked buffer.") | |
1230 | ||
1231 | (defun python-pdbtrack-get-or-add-tracking-buffers () | |
1232 | "Get/Add a tracked buffer for the current buffer. | |
1233 | Internally it uses the `python-pdbtrack-tracking-buffers' alist. | |
1234 | Returns a cons with the form: | |
1235 | * (#<tracking buffer> . #< tracked buffer>)." | |
1236 | (or | |
1237 | (assq (current-buffer) python-pdbtrack-tracking-buffers) | |
1238 | (let* ((file (with-current-buffer (current-buffer) | |
1239 | (or inferior-python-mode-current-file | |
1240 | inferior-python-mode-current-temp-file))) | |
1241 | (tracking-buffers | |
1242 | `(,(current-buffer) . | |
1243 | ,(or (get-file-buffer file) | |
1244 | (find-file-noselect file))))) | |
1245 | (set-buffer (cdr tracking-buffers)) | |
1246 | (python-mode) | |
1247 | (set-buffer (car tracking-buffers)) | |
1248 | (setq python-pdbtrack-tracking-buffers | |
1249 | (cons tracking-buffers python-pdbtrack-tracking-buffers)) | |
1250 | tracking-buffers))) | |
1251 | ||
1252 | (defun python-pdbtrack-comint-output-filter-function (output) | |
1253 | "Move overlay arrow to current pdb line in tracked buffer. | |
1254 | Argument OUTPUT is a string with the output from the comint process." | |
1255 | (when (not (string= output "")) | |
1256 | (let ((full-output (ansi-color-filter-apply | |
1257 | (buffer-substring comint-last-input-end | |
1258 | (point-max))))) | |
1259 | (if (string-match python-shell-prompt-pdb-regexp full-output) | |
1260 | (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers)) | |
1261 | (line-num | |
1262 | (save-excursion | |
1263 | (string-match | |
1264 | (format python-pdbtrack-stacktrace-info-regexp | |
1265 | (regexp-quote | |
1266 | inferior-python-mode-current-temp-file)) | |
1267 | full-output) | |
1268 | (string-to-number (or (match-string-no-properties 1 full-output) "")))) | |
1269 | (tracked-buffer-window (get-buffer-window (cdr tracking-buffers))) | |
1270 | (tracked-buffer-line-pos)) | |
1271 | (when line-num | |
1272 | (with-current-buffer (cdr tracking-buffers) | |
1273 | (set (make-local-variable 'overlay-arrow-string) "=>") | |
1274 | (set (make-local-variable 'overlay-arrow-position) (make-marker)) | |
1275 | (setq tracked-buffer-line-pos (progn | |
1276 | (goto-char (point-min)) | |
1277 | (forward-line (1- line-num)) | |
1278 | (point-marker))) | |
1279 | (when tracked-buffer-window | |
1280 | (set-window-point tracked-buffer-window tracked-buffer-line-pos)) | |
1281 | (set-marker overlay-arrow-position tracked-buffer-line-pos))) | |
1282 | (pop-to-buffer (cdr tracking-buffers)) | |
1283 | (switch-to-buffer-other-window (car tracking-buffers))) | |
1284 | (let ((tracking-buffers (assq (current-buffer) | |
1285 | python-pdbtrack-tracking-buffers))) | |
1286 | (when tracking-buffers | |
1287 | (if inferior-python-mode-current-file | |
1288 | (with-current-buffer (cdr tracking-buffers) | |
1289 | (set-marker overlay-arrow-position nil)) | |
1290 | (kill-buffer (cdr tracking-buffers))) | |
1291 | (setq python-pdbtrack-tracking-buffers | |
1292 | (assq-delete-all (current-buffer) | |
1293 | python-pdbtrack-tracking-buffers))))))) | |
1294 | output) | |
1295 | ||
1296 | \f | |
1297 | ;;; Symbol completion | |
1298 | ||
1299 | (defun python-completion-complete-at-point () | |
1300 | "Complete current symbol at point. | |
1301 | For this to work the best as possible you should call | |
1302 | `python-shell-send-buffer' from time to time so context in | |
1303 | inferior python process is updated properly." | |
1304 | (interactive) | |
1305 | (let ((process (python-shell-get-process))) | |
1306 | (if (not process) | |
4e531f7a | 1307 | (error "Completion needs an inferior Python process running") |
075a0f61 FEG |
1308 | (with-syntax-table python-dotty-syntax-table |
1309 | (let* ((input (substring-no-properties | |
1310 | (or (comint-word (current-word)) "") nil nil)) | |
1311 | (completions (python-shell-completion--get-completions | |
1312 | input process))) | |
1313 | (delete-char (- (length input))) | |
1314 | (insert | |
1315 | (python-shell-completion--get-completion | |
1316 | input completions))))))) | |
45c138ac FEG |
1317 | |
1318 | (add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.") | |
1319 | ||
1320 | \f | |
1321 | ;;; Fill paragraph | |
1322 | ||
1323 | (defun python-fill-paragraph-function (&optional justify) | |
1324 | "`fill-paragraph-function' handling multi-line strings and possibly comments. | |
1325 | If any of the current line is in or at the end of a multi-line string, | |
1326 | fill the string or the paragraph of it that point is in, preserving | |
4e531f7a FEG |
1327 | the string's indentation. |
1328 | Optional argument JUSTIFY defines if the paragraph should be justified." | |
45c138ac FEG |
1329 | (interactive "P") |
1330 | (save-excursion | |
1331 | (back-to-indentation) | |
1332 | (cond | |
1333 | ;; Comments | |
1334 | ((fill-comment-paragraph justify)) | |
1335 | ;; Docstrings | |
1336 | ((save-excursion (skip-chars-forward "\"'uUrR") | |
1337 | (nth 3 (syntax-ppss))) | |
1338 | (let ((marker (point-marker)) | |
1339 | (string-start-marker | |
1340 | (progn | |
1341 | (skip-chars-forward "\"'uUrR") | |
1342 | (goto-char (nth 8 (syntax-ppss))) | |
1343 | (skip-chars-forward "\"'uUrR") | |
1344 | (point-marker))) | |
1345 | (reg-start (line-beginning-position)) | |
1346 | (string-end-marker | |
1347 | (progn | |
1348 | (while (nth 3 (syntax-ppss)) (goto-char (1+ (point-marker)))) | |
1349 | (skip-chars-backward "\"'") | |
1350 | (point-marker))) | |
1351 | (reg-end (line-end-position)) | |
1352 | (fill-paragraph-function)) | |
1353 | (save-restriction | |
1354 | (narrow-to-region reg-start reg-end) | |
1355 | (save-excursion | |
1356 | (goto-char string-start-marker) | |
1357 | (delete-region (point-marker) (progn | |
1358 | (skip-syntax-forward "> ") | |
1359 | (point-marker))) | |
1360 | (goto-char string-end-marker) | |
1361 | (delete-region (point-marker) (progn | |
1362 | (skip-syntax-backward "> ") | |
1363 | (point-marker))) | |
1364 | (save-excursion | |
1365 | (goto-char marker) | |
1366 | (fill-paragraph justify)) | |
1367 | ;; If there is a newline in the docstring lets put triple | |
1368 | ;; quote in it's own line to follow pep 8 | |
1369 | (when (save-excursion | |
1370 | (re-search-backward "\n" string-start-marker t)) | |
1371 | (newline) | |
1372 | (newline-and-indent)) | |
1373 | (fill-paragraph justify)))) t) | |
1374 | ;; Decorators | |
1375 | ((equal (char-after (save-excursion | |
1376 | (back-to-indentation) | |
1377 | (point-marker))) ?@) t) | |
1378 | ;; Parens | |
1379 | ((or (> (nth 0 (syntax-ppss)) 0) | |
1380 | (looking-at (python-rx open-paren)) | |
1381 | (save-excursion | |
1382 | (skip-syntax-forward "^(" (line-end-position)) | |
1383 | (looking-at (python-rx open-paren)))) | |
1384 | (save-restriction | |
1385 | (narrow-to-region (progn | |
1386 | (while (> (nth 0 (syntax-ppss)) 0) | |
1387 | (goto-char (1- (point-marker)))) | |
1388 | (point-marker) | |
1389 | (line-beginning-position)) | |
1390 | (progn | |
1391 | (when (not (> (nth 0 (syntax-ppss)) 0)) | |
1392 | (end-of-line) | |
1393 | (when (not (> (nth 0 (syntax-ppss)) 0)) | |
1394 | (skip-syntax-backward "^)"))) | |
1395 | (while (> (nth 0 (syntax-ppss)) 0) | |
1396 | (goto-char (1+ (point-marker)))) | |
1397 | (point-marker))) | |
1398 | (let ((paragraph-start "\f\\|[ \t]*$") | |
1399 | (paragraph-separate ",") | |
1400 | (fill-paragraph-function)) | |
1401 | (goto-char (point-min)) | |
1402 | (fill-paragraph justify)) | |
1403 | (while (not (eobp)) | |
1404 | (forward-line 1) | |
1405 | (python-indent-line) | |
1406 | (goto-char (line-end-position)))) t) | |
1407 | (t t)))) | |
1408 | ||
1409 | \f | |
1410 | ;;; Eldoc | |
1411 | ||
1412 | (defvar python-eldoc-setup-code | |
1413 | "def __PYDOC_get_help(obj): | |
1414 | try: | |
1415 | import pydoc | |
1416 | obj = eval(obj, globals()) | |
1417 | return pydoc.getdoc(obj) | |
1418 | except: | |
1419 | return ''" | |
1420 | "Python code to setup documentation retrieval.") | |
1421 | ||
1422 | (defvar python-eldoc-string-code | |
1423 | "print __PYDOC_get_help('''%s''')\n" | |
1424 | "Python code used to get a string with the documentation of an object.") | |
1425 | ||
1426 | (defun python-eldoc-setup () | |
1427 | "Send `python-eldoc-setup-code' to inferior Python process. | |
1428 | It is specially designed to be added to the | |
1429 | `inferior-python-mode-hook'." | |
1430 | (when python-eldoc-setup-code | |
1431 | (let ((temp-file (make-temp-file "py"))) | |
1432 | (with-temp-file temp-file | |
1433 | (insert python-eldoc-setup-code) | |
1434 | (delete-trailing-whitespace) | |
1435 | (goto-char (point-min))) | |
66b0b492 | 1436 | (python-shell-send-file temp-file (get-buffer-process (current-buffer))) |
45c138ac FEG |
1437 | (message (format "Completion setup code sent."))))) |
1438 | ||
1439 | (defun python-eldoc-function () | |
1440 | "`eldoc-documentation-function' for Python. | |
1441 | For this to work the best as possible you should call | |
1442 | `python-shell-send-buffer' from time to time so context in | |
1443 | inferior python process is updated properly." | |
1444 | (interactive) | |
1445 | (let ((process (python-shell-get-process))) | |
1446 | (if (not process) | |
1447 | "Eldoc needs an inferior Python process running." | |
1448 | (let* ((current-defun (python-info-current-defun)) | |
1449 | (input (with-syntax-table python-dotty-syntax-table | |
1450 | (if (not current-defun) | |
1451 | (current-word) | |
1452 | (concat current-defun "." (current-word))))) | |
1453 | (ppss (syntax-ppss)) | |
1454 | (help (when (and input | |
1455 | (not (string= input (concat current-defun "."))) | |
1456 | (eq nil (nth 3 ppss)) | |
1457 | (eq nil (nth 4 ppss))) | |
1458 | (when (string-match (concat | |
1459 | (regexp-quote (concat current-defun ".")) | |
1460 | "self\\.") input) | |
1461 | (with-temp-buffer | |
1462 | (insert input) | |
1463 | (goto-char (point-min)) | |
1464 | (forward-word) | |
1465 | (forward-char) | |
1466 | (delete-region (point-marker) (search-forward "self.")) | |
1467 | (setq input (buffer-substring (point-min) (point-max))))) | |
1468 | (process-send-string | |
1469 | process (format python-eldoc-string-code input)) | |
1470 | (accept-process-output process) | |
1471 | (with-current-buffer (process-buffer process) | |
1472 | (when comint-last-prompt-overlay | |
1473 | (save-excursion | |
1474 | (goto-char comint-last-input-end) | |
1475 | (re-search-forward comint-prompt-regexp | |
1476 | (line-end-position) t) | |
1477 | (buffer-substring-no-properties | |
1478 | (point-marker) | |
1479 | (overlay-start comint-last-prompt-overlay)))))))) | |
1480 | (with-current-buffer (process-buffer process) | |
1481 | (when comint-last-prompt-overlay | |
1482 | (delete-region comint-last-input-end | |
1483 | (overlay-start comint-last-prompt-overlay)))) | |
1484 | (when (and help | |
1485 | (not (string= help "\n"))) | |
1486 | help))))) | |
1487 | ||
1488 | (add-hook 'inferior-python-mode-hook | |
1489 | #'python-eldoc-setup) | |
1490 | ||
1491 | \f | |
1492 | ;;; Misc helpers | |
1493 | ||
1494 | (defun python-info-current-defun () | |
1495 | "Return name of surrounding function with Python compatible dotty syntax. | |
1496 | This function is compatible to be used as | |
1497 | `add-log-current-defun-function' since it returns nil if point is | |
1498 | not inside a defun." | |
1499 | (let ((names '())) | |
1500 | (save-restriction | |
1501 | (widen) | |
1502 | (save-excursion | |
1503 | (beginning-of-line) | |
1504 | (when (not (>= (current-indentation) python-indent-offset)) | |
1505 | (while (and (not (eobp)) (forward-comment 1)))) | |
1506 | (while (and (not (equal 0 (current-indentation))) | |
1507 | (python-beginning-of-innermost-defun)) | |
1508 | (back-to-indentation) | |
1509 | (looking-at "\\(?:def\\|class\\) +\\([^(]+\\)[^:]+:\\s-*\n") | |
1510 | (setq names (cons (match-string-no-properties 1) names))))) | |
1511 | (when names | |
1512 | (mapconcat (lambda (string) string) names ".")))) | |
1513 | ||
1514 | (defun python-info-closing-block () | |
1515 | "Return the point of the block that the current line closes." | |
1516 | (let ((closing-word (save-excursion | |
1517 | (back-to-indentation) | |
1518 | (current-word))) | |
1519 | (indentation (current-indentation))) | |
1520 | (when (member closing-word python-indent-dedenters) | |
1521 | (save-excursion | |
1522 | (forward-line -1) | |
1523 | (while (and (> (current-indentation) indentation) | |
1524 | (not (bobp)) | |
1525 | (not (back-to-indentation)) | |
1526 | (forward-line -1))) | |
1527 | (back-to-indentation) | |
1528 | (cond | |
1529 | ((not (equal indentation (current-indentation))) nil) | |
1530 | ((string= closing-word "elif") | |
1531 | (when (member (current-word) '("if" "elif")) | |
1532 | (point-marker))) | |
1533 | ((string= closing-word "else") | |
1534 | (when (member (current-word) '("if" "elif" "except" "for" "while")) | |
1535 | (point-marker))) | |
1536 | ((string= closing-word "except") | |
1537 | (when (member (current-word) '("try")) | |
1538 | (point-marker))) | |
1539 | ((string= closing-word "finally") | |
1540 | (when (member (current-word) '("except" "else")) | |
1541 | (point-marker)))))))) | |
1542 | ||
1543 | (defun python-info-line-ends-backslash-p () | |
1544 | "Return non-nil if current line ends with backslash." | |
1545 | (string= (or (ignore-errors | |
1546 | (buffer-substring | |
1547 | (line-end-position) | |
1548 | (- (line-end-position) 1))) "") "\\")) | |
1549 | ||
1550 | (defun python-info-continuation-line-p () | |
1551 | "Return non-nil if current line is continuation of another." | |
1552 | (or (python-info-line-ends-backslash-p) | |
1553 | (string-match ",[[:space:]]*$" (buffer-substring | |
1554 | (line-beginning-position) | |
1555 | (line-end-position))) | |
1556 | (save-excursion | |
1557 | (let ((innermost-paren (progn | |
1558 | (goto-char (line-end-position)) | |
1559 | (nth 1 (syntax-ppss))))) | |
1560 | (when (and innermost-paren | |
1561 | (and (<= (line-beginning-position) innermost-paren) | |
1562 | (>= (line-end-position) innermost-paren))) | |
1563 | (goto-char innermost-paren) | |
1564 | (looking-at (python-rx open-paren (* space) line-end))))) | |
1565 | (save-excursion | |
1566 | (back-to-indentation) | |
1567 | (nth 1 (syntax-ppss))))) | |
1568 | ||
1569 | (defun python-info-block-continuation-line-p () | |
1570 | "Return non-nil if current line is a continuation of a block." | |
1571 | (save-excursion | |
1572 | (while (and (not (bobp)) | |
1573 | (python-info-continuation-line-p)) | |
1574 | (forward-line -1)) | |
1575 | (forward-line 1) | |
1576 | (back-to-indentation) | |
1577 | (when (looking-at (python-rx block-start)) | |
1578 | (point-marker)))) | |
1579 | ||
1580 | (defun python-info-assignment-continuation-line-p () | |
1581 | "Return non-nil if current line is a continuation of an assignment." | |
1582 | (save-excursion | |
1583 | (while (and (not (bobp)) | |
1584 | (python-info-continuation-line-p)) | |
1585 | (forward-line -1)) | |
1586 | (forward-line 1) | |
1587 | (back-to-indentation) | |
1588 | (when (and (not (looking-at (python-rx block-start))) | |
1589 | (save-excursion | |
1590 | (and (re-search-forward (python-rx not-simple-operator | |
1591 | assignment-operator | |
1592 | not-simple-operator) | |
1593 | (line-end-position) t) | |
1594 | (not (syntax-ppss-context (syntax-ppss)))))) | |
1595 | (point-marker)))) | |
1596 | ||
1597 | \f | |
1598 | ;;;###autoload | |
1599 | (define-derived-mode python-mode fundamental-mode "Python" | |
1600 | "A major mode for editing Python files." | |
1601 | (set (make-local-variable 'tab-width) 8) | |
1602 | (set (make-local-variable 'indent-tabs-mode) nil) | |
1603 | ||
1604 | (set (make-local-variable 'comment-start) "# ") | |
1605 | (set (make-local-variable 'comment-start-skip) "#+\\s-*") | |
1606 | ||
1607 | (set (make-local-variable 'parse-sexp-lookup-properties) t) | |
1608 | (set (make-local-variable 'parse-sexp-ignore-comments) t) | |
1609 | ||
1610 | (set (make-local-variable 'font-lock-defaults) | |
1611 | '(python-font-lock-keywords | |
1612 | nil nil nil nil | |
1613 | (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords))) | |
1614 | ||
1615 | (set (make-local-variable 'indent-line-function) #'python-indent-line-function) | |
1616 | (set (make-local-variable 'indent-region-function) #'python-indent-region) | |
1617 | ||
1618 | (set (make-local-variable 'paragraph-start) "\\s-*$") | |
1619 | (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function) | |
1620 | ||
1621 | (set (make-local-variable 'beginning-of-defun-function) | |
1622 | #'python-beginning-of-defun-function) | |
1623 | (set (make-local-variable 'end-of-defun-function) | |
1624 | #'python-end-of-defun-function) | |
1625 | ||
1626 | (add-hook 'completion-at-point-functions | |
1627 | 'python-completion-complete-at-point nil 'local) | |
1628 | ||
1629 | (set (make-local-variable 'add-log-current-defun-function) | |
1630 | #'python-info-current-defun) | |
1631 | ||
1632 | (set (make-local-variable 'eldoc-documentation-function) | |
1633 | #'python-eldoc-function) | |
1634 | ||
1635 | (add-to-list 'hs-special-modes-alist | |
1636 | `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#" | |
1637 | ,(lambda (arg) | |
1638 | (python-end-of-defun-function)) nil)) | |
1639 | ||
1640 | (set (make-local-variable 'outline-regexp) | |
1641 | (python-rx (* space) block-start)) | |
1642 | (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n") | |
1643 | (set (make-local-variable 'outline-level) | |
1644 | #'(lambda () | |
1645 | "`outline-level' function for Python mode." | |
1646 | (1+ (/ (current-indentation) python-indent-offset)))) | |
1647 | ||
1648 | (when python-indent-guess-indent-offset | |
1649 | (python-indent-guess-indent-offset))) | |
1650 | ||
1651 | ||
1652 | (provide 'python) | |
1653 | ;;; python.el ends here |