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