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