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