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