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