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