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