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