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