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