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