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