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