calccomp.el (math-compose-expr): Undo previous change.
[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
30e429dd
FEG
1357(defcustom python-shell-send-setup-max-wait 5
1358 "Seconds to wait for process output before code setup.
48d1354e 1359If output is received before the specified time then control is
30e429dd 1360returned in that moment and not after waiting."
0f55249e 1361 :type 'integer
30e429dd 1362 :group 'python
0f55249e 1363 :safe 'integerp)
30e429dd 1364
66bbb27f 1365(defcustom python-shell-process-environment nil
307bd2e8
FEG
1366 "List of environment variables for Python shell.
1367This variable follows the same rules as `process-environment'
66bbb27f
FEG
1368since it merges with it before the process creation routines are
1369called. When this variable is nil, the Python shell is run with
307bd2e8 1370the default `process-environment'."
66bbb27f
FEG
1371 :type '(repeat string)
1372 :group 'python
1373 :safe 'listp)
1374
929036b4
FEG
1375(defcustom python-shell-extra-pythonpaths nil
1376 "List of extra pythonpaths for Python shell.
1377The values of this variable are added to the existing value of
1378PYTHONPATH in the `process-environment' variable."
1379 :type '(repeat string)
1380 :group 'python
1381 :safe 'listp)
1382
66bbb27f
FEG
1383(defcustom python-shell-exec-path nil
1384 "List of path to search for binaries.
1385This variable follows the same rules as `exec-path' since it
1386merges with it before the process creation routines are called.
1387When this variable is nil, the Python shell is run with the
1388default `exec-path'."
1389 :type '(repeat string)
1390 :group 'python
1391 :safe 'listp)
1392
64348c32
FEG
1393(defcustom python-shell-virtualenv-path nil
1394 "Path to virtualenv root.
1395This variable, when set to a string, makes the values stored in
1396`python-shell-process-environment' and `python-shell-exec-path'
1397to be modified properly so shells are started with the specified
1398virtualenv."
1399 :type 'string
1400 :group 'python
1401 :safe 'stringp)
1402
c0428ba0
FEG
1403(defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1404 python-ffap-setup-code
1405 python-eldoc-setup-code)
279c9272 1406 "List of code run by `python-shell-send-setup-codes'."
c0428ba0
FEG
1407 :type '(repeat symbol)
1408 :group 'python
1409 :safe 'listp)
1410
45c138ac
FEG
1411(defcustom python-shell-compilation-regexp-alist
1412 `((,(rx line-start (1+ (any " \t")) "File \""
6cad4c6e
FEG
1413 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1414 "\", line " (group (1+ digit)))
45c138ac
FEG
1415 1 2)
1416 (,(rx " in file " (group (1+ not-newline)) " on line "
6cad4c6e 1417 (group (1+ digit)))
45c138ac
FEG
1418 1 2)
1419 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
6cad4c6e 1420 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
45c138ac
FEG
1421 1 2))
1422 "`compilation-error-regexp-alist' for inferior Python."
1423 :type '(alist string)
1424 :group 'python)
1425
1426(defun python-shell-get-process-name (dedicated)
e37a4551 1427 "Calculate the appropriate process name for inferior Python process.
45c138ac
FEG
1428If DEDICATED is t and the variable `buffer-file-name' is non-nil
1429returns a string with the form
1430`python-shell-buffer-name'[variable `buffer-file-name'] else
e2d8d479
FEG
1431returns the value of `python-shell-buffer-name'. After
1432calculating the process name adds the buffer name for the process
1433in the `same-window-buffer-names' list."
45c138ac
FEG
1434 (let ((process-name
1435 (if (and dedicated
1436 buffer-file-name)
1437 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1438 (format "%s" python-shell-buffer-name))))
1439 (add-to-list 'same-window-buffer-names (purecopy
1440 (format "*%s*" process-name)))
1441 process-name))
1442
1fe1b5aa 1443(defun python-shell-internal-get-process-name ()
e37a4551 1444 "Calculate the appropriate process name for Internal Python process.
1fe1b5aa
FEG
1445The name is calculated from `python-shell-global-buffer-name' and
1446a hash of all relevant global shell settings in order to ensure
1447uniqueness for different types of configurations."
1448 (format "%s [%s]"
1449 python-shell-internal-buffer-name
1450 (md5
1451 (concat
1452 (python-shell-parse-command)
279c9272
FEG
1453 python-shell-prompt-regexp
1454 python-shell-prompt-block-regexp
1455 python-shell-prompt-output-regexp
1fe1b5aa 1456 (mapconcat #'symbol-value python-shell-setup-codes "")
2bdce388
FEG
1457 (mapconcat #'identity python-shell-process-environment "")
1458 (mapconcat #'identity python-shell-extra-pythonpaths "")
1459 (mapconcat #'identity python-shell-exec-path "")
64348c32 1460 (or python-shell-virtualenv-path "")
2bdce388 1461 (mapconcat #'identity python-shell-exec-path "")))))
1fe1b5aa 1462
45c138ac 1463(defun python-shell-parse-command ()
e2d8d479 1464 "Calculate the string used to execute the inferior Python process."
45c138ac
FEG
1465 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1466
307bd2e8
FEG
1467(defun python-shell-calculate-process-environment ()
1468 "Calculate process environment given `python-shell-virtualenv-path'."
40417cb3
FEG
1469 (let ((process-environment (append
1470 python-shell-process-environment
1471 process-environment nil))
64348c32
FEG
1472 (virtualenv (if python-shell-virtualenv-path
1473 (directory-file-name python-shell-virtualenv-path)
1474 nil)))
929036b4
FEG
1475 (when python-shell-extra-pythonpaths
1476 (setenv "PYTHONPATH"
1477 (format "%s%s%s"
1478 (mapconcat 'identity
1479 python-shell-extra-pythonpaths
1480 path-separator)
1481 path-separator
1482 (or (getenv "PYTHONPATH") ""))))
64348c32 1483 (if (not virtualenv)
40417cb3
FEG
1484 process-environment
1485 (setenv "PYTHONHOME" nil)
1486 (setenv "PATH" (format "%s/bin%s%s"
929036b4
FEG
1487 virtualenv path-separator
1488 (or (getenv "PATH") "")))
40417cb3
FEG
1489 (setenv "VIRTUAL_ENV" virtualenv))
1490 process-environment))
64348c32
FEG
1491
1492(defun python-shell-calculate-exec-path ()
1493 "Calculate exec path given `python-shell-virtualenv-path'."
40417cb3
FEG
1494 (let ((path (append python-shell-exec-path
1495 exec-path nil)))
64348c32
FEG
1496 (if (not python-shell-virtualenv-path)
1497 path
1498 (cons (format "%s/bin"
1499 (directory-file-name python-shell-virtualenv-path))
1500 path))))
1501
45c138ac
FEG
1502(defun python-comint-output-filter-function (output)
1503 "Hook run after content is put into comint buffer.
1504OUTPUT is a string with the contents of the buffer."
1505 (ansi-color-filter-apply output))
1506
45c138ac 1507(define-derived-mode inferior-python-mode comint-mode "Inferior Python"
62feb915 1508 "Major mode for Python inferior process.
e2d8d479
FEG
1509Runs a Python interpreter as a subprocess of Emacs, with Python
1510I/O through an Emacs buffer. Variables
1511`python-shell-interpreter' and `python-shell-interpreter-args'
1512controls which Python interpreter is run. Variables
1513`python-shell-prompt-regexp',
1514`python-shell-prompt-output-regexp',
1515`python-shell-prompt-block-regexp',
a7a6d8ff 1516`python-shell-enable-font-lock',
e2d8d479 1517`python-shell-completion-setup-code',
9399498e 1518`python-shell-completion-string-code',
f6b59cd1 1519`python-shell-completion-module-string-code',
9399498e
FEG
1520`python-eldoc-setup-code', `python-eldoc-string-code',
1521`python-ffap-setup-code' and `python-ffap-string-code' can
1522customize this mode for different Python interpreters.
e2d8d479
FEG
1523
1524You can also add additional setup code to be run at
1525initialization of the interpreter via `python-shell-setup-codes'
1526variable.
1527
1528\(Type \\[describe-mode] in the process buffer for a list of commands.)"
45c138ac
FEG
1529 (set-syntax-table python-mode-syntax-table)
1530 (setq mode-line-process '(":%s"))
1531 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1532 python-shell-prompt-regexp
1533 python-shell-prompt-block-regexp
1534 python-shell-prompt-pdb-regexp))
1535 (make-local-variable 'comint-output-filter-functions)
1536 (add-hook 'comint-output-filter-functions
1537 'python-comint-output-filter-function)
1538 (add-hook 'comint-output-filter-functions
1539 'python-pdbtrack-comint-output-filter-function)
1540 (set (make-local-variable 'compilation-error-regexp-alist)
1541 python-shell-compilation-regexp-alist)
ed0eb594
FEG
1542 (define-key inferior-python-mode-map [remap complete-symbol]
1543 'completion-at-point)
1544 (add-hook 'completion-at-point-functions
1545 'python-shell-completion-complete-at-point nil 'local)
62feb915
FEG
1546 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1547 'python-shell-completion-complete-at-point)
1548 (define-key inferior-python-mode-map (kbd "<tab>")
1549 'python-shell-completion-complete-or-indent)
a7a6d8ff 1550 (when python-shell-enable-font-lock
aeadd9a4
FEG
1551 (set (make-local-variable 'font-lock-defaults)
1552 '(python-font-lock-keywords nil nil nil nil))
1553 (set (make-local-variable 'syntax-propertize-function)
1554 python-syntax-propertize-function))
45c138ac
FEG
1555 (compilation-shell-minor-mode 1))
1556
96eeb83a 1557(defun python-shell-make-comint (cmd proc-name &optional pop)
77afb61a 1558 "Create a python shell comint buffer.
96eeb83a 1559CMD is the python command to be executed and PROC-NAME is the
77afb61a 1560process name the comint buffer will get. After the comint buffer
96eeb83a
FEG
1561is created the `inferior-python-mode' is activated. If POP is
1562non-nil the buffer is shown."
77afb61a
FEG
1563 (save-excursion
1564 (let* ((proc-buffer-name (format "*%s*" proc-name))
307bd2e8 1565 (process-environment (python-shell-calculate-process-environment))
77afb61a
FEG
1566 (exec-path (python-shell-calculate-exec-path)))
1567 (when (not (comint-check-proc proc-buffer-name))
96eeb83a
FEG
1568 (let* ((cmdlist (split-string-and-unquote cmd))
1569 (buffer (apply 'make-comint proc-name (car cmdlist) nil
1570 (cdr cmdlist)))
d2190c57 1571 (current-buffer (current-buffer)))
96eeb83a
FEG
1572 (with-current-buffer buffer
1573 (inferior-python-mode)
fbc39529 1574 (python-util-clone-local-variables current-buffer))))
a90dfb95 1575 (and pop (pop-to-buffer proc-buffer-name t))
a0686d71 1576 proc-buffer-name)))
77afb61a 1577
a90dfb95
FEG
1578;;;###autoload
1579(defun run-python (cmd &optional dedicated show)
45c138ac 1580 "Run an inferior Python process.
e2d8d479
FEG
1581Input and output via buffer named after
1582`python-shell-buffer-name'. If there is a process already
1583running in that buffer, just switch to it.
a90dfb95
FEG
1584
1585With argument, allows you to define CMD so you can edit the
1586command used to call the interpreter and define DEDICATED, so a
1587dedicated process for the current buffer is open. When numeric
1588prefix arg is other than 0 or 4 do not SHOW.
1589
1590Runs the hook `inferior-python-mode-hook' (after the
1591`comint-mode-hook' is run). \(Type \\[describe-mode] in the
1592process buffer for a list of commands.)"
45c138ac
FEG
1593 (interactive
1594 (if current-prefix-arg
1595 (list
a90dfb95 1596 (read-string "Run Python: " (python-shell-parse-command))
45c138ac 1597 (y-or-n-p "Make dedicated process? ")
a90dfb95
FEG
1598 (= (prefix-numeric-value current-prefix-arg) 4))
1599 (list (python-shell-parse-command) nil t)))
1600 (python-shell-make-comint
1601 cmd (python-shell-get-process-name dedicated) show)
45c138ac
FEG
1602 dedicated)
1603
1fe1b5aa
FEG
1604(defun run-python-internal ()
1605 "Run an inferior Internal Python process.
1606Input and output via buffer named after
1607`python-shell-internal-buffer-name' and what
1608`python-shell-internal-get-process-name' returns. This new kind
1609of shell is intended to be used for generic communication related
1610to defined configurations. The main difference with global or
1611dedicated shells is that these ones are attached to a
1612configuration, not a buffer. This means that can be used for
1613example to retrieve the sys.path and other stuff, without messing
1614with user shells. Runs the hook
1615`inferior-python-mode-hook' (after the `comint-mode-hook' is
1616run). \(Type \\[describe-mode] in the process buffer for a list
1617of commands.)"
a0686d71
FEG
1618 (set-process-query-on-exit-flag
1619 (get-buffer-process
1620 (python-shell-make-comint
1621 (python-shell-parse-command)
1622 (python-shell-internal-get-process-name))) nil))
1fe1b5aa 1623
45c138ac
FEG
1624(defun python-shell-get-process ()
1625 "Get inferior Python process for current buffer and return it."
1626 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1627 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1628 (global-proc-name (python-shell-get-process-name nil))
1629 (global-proc-buffer-name (format "*%s*" global-proc-name))
1630 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1631 (global-running (comint-check-proc global-proc-buffer-name)))
1632 ;; Always prefer dedicated
1633 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1634 (and global-running global-proc-buffer-name)))))
1635
1636(defun python-shell-get-or-create-process ()
1637 "Get or create an inferior Python process for current buffer and return it."
035c45e3 1638 (let* ((dedicated-proc-name (python-shell-get-process-name t))
45c138ac
FEG
1639 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1640 (global-proc-name (python-shell-get-process-name nil))
1641 (global-proc-buffer-name (format "*%s*" global-proc-name))
1642 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1643 (global-running (comint-check-proc global-proc-buffer-name))
a90dfb95 1644 (current-prefix-arg 16))
45c138ac
FEG
1645 (when (and (not dedicated-running) (not global-running))
1646 (if (call-interactively 'run-python)
1647 (setq dedicated-running t)
1648 (setq global-running t)))
1649 ;; Always prefer dedicated
1650 (get-buffer-process (if dedicated-running
1651 dedicated-proc-buffer-name
1652 global-proc-buffer-name))))
1653
722c985b
FEG
1654(defvar python-shell-internal-buffer nil
1655 "Current internal shell buffer for the current buffer.
1656This is really not necessary at all for the code to work but it's
1657there for compatibility with CEDET.")
1658(make-variable-buffer-local 'python-shell-internal-buffer)
1659
1fe1b5aa
FEG
1660(defun python-shell-internal-get-or-create-process ()
1661 "Get or create an inferior Internal Python process."
1662 (let* ((proc-name (python-shell-internal-get-process-name))
1663 (proc-buffer-name (format "*%s*" proc-name)))
1664 (run-python-internal)
722c985b 1665 (setq python-shell-internal-buffer proc-buffer-name)
1fe1b5aa
FEG
1666 (get-buffer-process proc-buffer-name)))
1667
722c985b 1668(define-obsolete-function-alias
35647f79 1669 'python-proc 'python-shell-internal-get-or-create-process "24.2")
722c985b
FEG
1670
1671(define-obsolete-variable-alias
35647f79 1672 'python-buffer 'python-shell-internal-buffer "24.2")
722c985b 1673
9ce938be
FEG
1674(defun python-shell-send-string (string &optional process msg)
1675 "Send STRING to inferior Python PROCESS.
1676When MSG is non-nil messages the first line of STRING."
45c138ac 1677 (interactive "sPython command: ")
9ce938be
FEG
1678 (let ((process (or process (python-shell-get-or-create-process)))
1679 (lines (split-string string "\n" t)))
1680 (when msg
1681 (message (format "Sent: %s..." (nth 0 lines))))
1682 (if (> (length lines) 1)
1683 (let* ((temp-file-name (make-temp-file "py"))
1684 (file-name (or (buffer-file-name) temp-file-name)))
1685 (with-temp-file temp-file-name
1686 (insert string)
1687 (delete-trailing-whitespace))
1688 (python-shell-send-file file-name process temp-file-name))
1689 (comint-send-string process string)
1690 (when (or (not (string-match "\n$" string))
1691 (string-match "\n[ \t].*\n?$" string))
1692 (comint-send-string process "\n")))))
1693
1694(defun python-shell-send-string-no-output (string &optional process msg)
1695 "Send STRING to PROCESS and inhibit output.
e2d8d479
FEG
1696When MSG is non-nil messages the first line of STRING. Return
1697the output."
191da00e 1698 (let* ((output-buffer "")
9ce938be
FEG
1699 (process (or process (python-shell-get-or-create-process)))
1700 (comint-preoutput-filter-functions
1701 (append comint-preoutput-filter-functions
1702 '(ansi-color-filter-apply
1703 (lambda (string)
1704 (setq output-buffer (concat output-buffer string))
191da00e
FEG
1705 ""))))
1706 (inhibit-quit t))
1707 (or
1708 (with-local-quit
1709 (python-shell-send-string string process msg)
1710 (accept-process-output process)
1711 (replace-regexp-in-string
1712 (if (> (length python-shell-prompt-output-regexp) 0)
1713 (format "\n*%s$\\|^%s\\|\n$"
1714 python-shell-prompt-regexp
1715 (or python-shell-prompt-output-regexp ""))
1716 (format "\n*$\\|^%s\\|\n$"
1717 python-shell-prompt-regexp))
1718 "" output-buffer))
1719 (with-current-buffer (process-buffer process)
1720 (comint-interrupt-subjob)))))
45c138ac 1721
1fe1b5aa
FEG
1722(defun python-shell-internal-send-string (string)
1723 "Send STRING to the Internal Python interpreter.
1724Returns the output. See `python-shell-send-string-no-output'."
1725 (python-shell-send-string-no-output
1726 ;; Makes this function compatible with the old
1727 ;; python-send-receive. (At least for CEDET).
1728 (replace-regexp-in-string "_emacs_out +" "" string)
1729 (python-shell-internal-get-or-create-process) nil))
1730
1731(define-obsolete-function-alias
35647f79 1732 'python-send-receive 'python-shell-internal-send-string "24.2")
722c985b
FEG
1733
1734(define-obsolete-function-alias
35647f79 1735 'python-send-string 'python-shell-internal-send-string "24.2")
1fe1b5aa 1736
45c138ac
FEG
1737(defun python-shell-send-region (start end)
1738 "Send the region delimited by START and END to inferior Python process."
1739 (interactive "r")
bdfb840e 1740 (python-shell-send-string (buffer-substring start end) nil t))
45c138ac 1741
6da55e59
DD
1742(defun python-shell-send-buffer (&optional arg)
1743 "Send the entire buffer to inferior Python process.
1744
4289485a 1745With prefix ARG include lines surrounded by \"if __name__ == '__main__':\""
6da55e59 1746 (interactive "P")
45c138ac
FEG
1747 (save-restriction
1748 (widen)
6da55e59
DD
1749 (python-shell-send-region
1750 (point-min)
1751 (or (and
90a41b9d
FEG
1752 (not arg)
1753 (save-excursion
1754 (re-search-forward (python-rx if-name-main) nil t))
1755 (match-beginning 0))
1756 (point-max)))))
45c138ac
FEG
1757
1758(defun python-shell-send-defun (arg)
2ed294c5 1759 "Send the current defun to inferior Python process.
8c6f9e60 1760When argument ARG is non-nil do not include decorators."
45c138ac
FEG
1761 (interactive "P")
1762 (save-excursion
2ed294c5
FEG
1763 (python-shell-send-region
1764 (progn
8c6f9e60
FEG
1765 (end-of-line 1)
1766 (while (and (or (python-beginning-of-defun-function)
1767 (beginning-of-line 1))
1768 (> (current-indentation) 0)))
1769 (when (not arg)
1770 (while (and (forward-line -1)
1771 (looking-at (python-rx decorator))))
1772 (forward-line 1))
1dae378f 1773 (point-marker))
2ed294c5
FEG
1774 (progn
1775 (or (python-end-of-defun-function)
8c6f9e60 1776 (end-of-line 1))
1dae378f 1777 (point-marker)))))
45c138ac 1778
d439cda5
FEG
1779(defun python-shell-send-file (file-name &optional process temp-file-name)
1780 "Send FILE-NAME to inferior Python PROCESS.
1781If TEMP-FILE-NAME is passed then that file is used for processing
1782instead, while internally the shell will continue to use
1783FILE-NAME."
45c138ac 1784 (interactive "fFile to send: ")
9ce938be
FEG
1785 (let* ((process (or process (python-shell-get-or-create-process)))
1786 (temp-file-name (when temp-file-name
1787 (expand-file-name temp-file-name)))
1788 (file-name (or (expand-file-name file-name) temp-file-name)))
1789 (when (not file-name)
1790 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
13d914ed 1791 (python-shell-send-string
b962ebad 1792 (format
d439cda5
FEG
1793 (concat "__pyfile = open('''%s''');"
1794 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1795 "__pyfile.close()")
1796 (or temp-file-name file-name) file-name)
13d914ed 1797 process)))
45c138ac
FEG
1798
1799(defun python-shell-switch-to-shell ()
1800 "Switch to inferior Python process buffer."
1801 (interactive)
1802 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1803
c0428ba0
FEG
1804(defun python-shell-send-setup-code ()
1805 "Send all setup code for shell.
1806This function takes the list of setup code to send from the
1807`python-shell-setup-codes' list."
1808 (let ((msg "Sent %s")
1809 (process (get-buffer-process (current-buffer))))
30e429dd 1810 (accept-process-output process python-shell-send-setup-max-wait)
c0428ba0
FEG
1811 (dolist (code python-shell-setup-codes)
1812 (when code
c0428ba0 1813 (message (format msg code))
a1ea6ab8 1814 (python-shell-send-string
c0428ba0
FEG
1815 (symbol-value code) process)))))
1816
1817(add-hook 'inferior-python-mode-hook
1818 #'python-shell-send-setup-code)
1819
45c138ac
FEG
1820\f
1821;;; Shell completion
1822
0f55249e 1823(defcustom python-shell-completion-setup-code
45c138ac
FEG
1824 "try:
1825 import readline
1826except ImportError:
1827 def __COMPLETER_all_completions(text): []
1828else:
1829 import rlcompleter
1830 readline.set_completer(rlcompleter.Completer().complete)
1831 def __COMPLETER_all_completions(text):
1832 import sys
1833 completions = []
1834 try:
1835 i = 0
1836 while True:
1837 res = readline.get_completer()(text, i)
1838 if not res: break
1839 i += 1
1840 completions.append(res)
1841 except NameError:
1842 pass
1843 return completions"
0f55249e
FEG
1844 "Code used to setup completion in inferior Python processes."
1845 :type 'string
c4b155cb 1846 :group 'python)
45c138ac 1847
0f55249e 1848(defcustom python-shell-completion-string-code
45c138ac 1849 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
0f55249e
FEG
1850 "Python code used to get a string of completions separated by semicolons."
1851 :type 'string
c4b155cb 1852 :group 'python)
45c138ac 1853
f6b59cd1 1854(defcustom python-shell-completion-module-string-code ""
8386d830 1855 "Python code used to get completions separated by semicolons for imports.
9253ea69
DD
1856
1857For IPython v0.11, add the following line to
1858`python-shell-completion-setup-code':
1859
1860from IPython.core.completerlib import module_completion
1861
1862and use the following as the value of this variable:
1863
1864';'.join(module_completion('''%s'''))\n"
1865 :type 'string
c4b155cb 1866 :group 'python)
9253ea69 1867
aa409935
FEG
1868(defcustom python-shell-completion-pdb-string-code
1869 "';'.join(globals().keys() + locals().keys())"
1870 "Python code used to get completions separated by semicolons for [i]pdb."
1871 :type 'string
c4b155cb 1872 :group 'python)
aa409935 1873
9253ea69 1874(defun python-shell-completion--get-completions (input process completion-code)
8386d830
FEG
1875 "Retrieve available completions for INPUT using PROCESS.
1876Argument COMPLETION-CODE is the python code used to get
1877completions on the current context."
075a0f61 1878 (with-current-buffer (process-buffer process)
62feb915 1879 (let ((completions (python-shell-send-string-no-output
9253ea69 1880 (format completion-code input) process)))
62feb915
FEG
1881 (when (> (length completions) 2)
1882 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
075a0f61 1883
b71bfa9c 1884(defun python-shell-completion--do-completion-at-point (process)
8386d830 1885 "Do completion at point for PROCESS."
b71bfa9c 1886 (with-syntax-table python-dotty-syntax-table
cb37c7e3
FEG
1887 (let* ((beg
1888 (save-excursion
1889 (let* ((paren-depth (car (syntax-ppss)))
1890 (syntax-string "w_")
1891 (syntax-list (string-to-syntax syntax-string)))
1892 ;; Stop scanning for the beginning of the completion subject
1893 ;; after the char before point matches a delimiter
1894 (while (member (car (syntax-after (1- (point)))) syntax-list)
1895 (skip-syntax-backward syntax-string)
1896 (when (or (equal (char-before) ?\))
1897 (equal (char-before) ?\"))
1898 (forward-char -1))
1899 (while (or
1900 ;; honor initial paren depth
1901 (> (car (syntax-ppss)) paren-depth)
1902 (python-info-ppss-context 'string))
1903 (forward-char -1))))
1904 (point)))
0d0e6ccd
FEG
1905 (end (point))
1906 (line (buffer-substring-no-properties (point-at-bol) end))
1907 (input (buffer-substring-no-properties beg end))
1908 ;; Get the last prompt for the inferior process buffer. This is
1909 ;; used for the completion code selection heuristic.
394f09a3
FEG
1910 (prompt
1911 (with-current-buffer (process-buffer process)
1912 (buffer-substring-no-properties
1913 (overlay-start comint-last-prompt-overlay)
1914 (overlay-end comint-last-prompt-overlay))))
53df7818 1915 (completion-context
48d1354e 1916 ;; Check whether a prompt matches a pdb string, an import statement
0d0e6ccd
FEG
1917 ;; or just the standard prompt and use the correct
1918 ;; python-shell-completion-*-code string
aa409935 1919 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
338a21d0
FEG
1920 (string-match
1921 (concat "^" python-shell-prompt-pdb-regexp) prompt))
53df7818 1922 'pdb)
6cad4c6e
FEG
1923 ((and (>
1924 (length python-shell-completion-module-string-code) 0)
338a21d0
FEG
1925 (string-match
1926 (concat "^" python-shell-prompt-regexp) prompt)
39806de3 1927 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line))
53df7818 1928 'import)
338a21d0
FEG
1929 ((string-match
1930 (concat "^" python-shell-prompt-regexp) prompt)
53df7818 1931 'default)
338a21d0 1932 (t nil)))
90a41b9d
FEG
1933 (completion-code
1934 (case completion-context
1935 ('pdb python-shell-completion-pdb-string-code)
1936 ('import python-shell-completion-module-string-code)
1937 ('default python-shell-completion-string-code)
1938 (t nil)))
1939 (input
1940 (if (eq completion-context 'import)
1941 (replace-regexp-in-string "^[ \t]+" "" line)
1942 input))
aa409935 1943 (completions
338a21d0
FEG
1944 (and completion-code (> (length input) 0)
1945 (python-shell-completion--get-completions
cb37c7e3 1946 input process completion-code))))
0d0e6ccd 1947 (list beg end completions))))
075a0f61 1948
45c138ac
FEG
1949(defun python-shell-completion-complete-at-point ()
1950 "Perform completion at point in inferior Python process."
1951 (interactive)
b71bfa9c
DD
1952 (and comint-last-prompt-overlay
1953 (> (point-marker) (overlay-end comint-last-prompt-overlay))
1954 (python-shell-completion--do-completion-at-point
6cad4c6e 1955 (get-buffer-process (current-buffer)))))
45c138ac 1956
45c138ac
FEG
1957(defun python-shell-completion-complete-or-indent ()
1958 "Complete or indent depending on the context.
e2d8d479
FEG
1959If content before pointer is all whitespace indent. If not try
1960to complete."
45c138ac
FEG
1961 (interactive)
1962 (if (string-match "^[[:space:]]*$"
1963 (buffer-substring (comint-line-beginning-position)
1964 (point-marker)))
1965 (indent-for-tab-command)
799aa2af 1966 (completion-at-point)))
45c138ac 1967
45c138ac
FEG
1968\f
1969;;; PDB Track integration
1970
76a9ea3b
FEG
1971(defcustom python-pdbtrack-activate t
1972 "Non-nil makes python shell enable pdbtracking."
1973 :type 'boolean
1974 :group 'python
1975 :safe 'booleanp)
1976
0f55249e 1977(defcustom python-pdbtrack-stacktrace-info-regexp
aeac8c27 1978 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
e2d8d479 1979 "Regular Expression matching stacktrace information.
aeac8c27 1980Used to extract the current line and module being inspected."
0f55249e
FEG
1981 :type 'string
1982 :group 'python
1983 :safe 'stringp)
45c138ac 1984
e1f00930
FEG
1985(defvar python-pdbtrack-tracked-buffer nil
1986 "Variable containing the value of the current tracked buffer.
1987Never set this variable directly, use
1988`python-pdbtrack-set-tracked-buffer' instead.")
1989(make-variable-buffer-local 'python-pdbtrack-tracked-buffer)
1990
1991(defvar python-pdbtrack-buffers-to-kill nil
1992 "List of buffers to be deleted after tracking finishes.")
1993(make-variable-buffer-local 'python-pdbtrack-buffers-to-kill)
1994
1995(defun python-pdbtrack-set-tracked-buffer (file-name)
1996 "Set the buffer for FILE-NAME as the tracked buffer.
1997Internally it uses the `python-pdbtrack-tracked-buffer' variable.
1998Returns the tracked buffer."
1999 (let ((file-buffer (get-file-buffer file-name)))
2000 (if file-buffer
2001 (setq python-pdbtrack-tracked-buffer file-buffer)
2002 (setq file-buffer (find-file-noselect file-name))
2003 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
2004 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
2005 file-buffer))
45c138ac
FEG
2006
2007(defun python-pdbtrack-comint-output-filter-function (output)
2008 "Move overlay arrow to current pdb line in tracked buffer.
2009Argument OUTPUT is a string with the output from the comint process."
76a9ea3b 2010 (when (and python-pdbtrack-activate (not (string= output "")))
aeac8c27
FEG
2011 (let* ((full-output (ansi-color-filter-apply
2012 (buffer-substring comint-last-input-end (point-max))))
2013 (line-number)
2014 (file-name
2015 (with-temp-buffer
aeac8c27
FEG
2016 (insert full-output)
2017 (goto-char (point-min))
e1f00930
FEG
2018 ;; OK, this sucked but now it became a cool hack. The
2019 ;; stacktrace information normally is on the first line
2020 ;; but in some cases (like when doing a step-in) it is
2021 ;; on the second.
2022 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp)
6cad4c6e
FEG
2023 (and
2024 (forward-line)
2025 (looking-at python-pdbtrack-stacktrace-info-regexp)))
aeac8c27
FEG
2026 (setq line-number (string-to-number
2027 (match-string-no-properties 2)))
2028 (match-string-no-properties 1)))))
2029 (if (and file-name line-number)
6cad4c6e
FEG
2030 (let* ((tracked-buffer
2031 (python-pdbtrack-set-tracked-buffer file-name))
e1f00930
FEG
2032 (shell-buffer (current-buffer))
2033 (tracked-buffer-window (get-buffer-window tracked-buffer))
45c138ac 2034 (tracked-buffer-line-pos))
e1f00930 2035 (with-current-buffer tracked-buffer
aeac8c27
FEG
2036 (set (make-local-variable 'overlay-arrow-string) "=>")
2037 (set (make-local-variable 'overlay-arrow-position) (make-marker))
2038 (setq tracked-buffer-line-pos (progn
2039 (goto-char (point-min))
2040 (forward-line (1- line-number))
2041 (point-marker)))
2042 (when tracked-buffer-window
2043 (set-window-point
2044 tracked-buffer-window tracked-buffer-line-pos))
2045 (set-marker overlay-arrow-position tracked-buffer-line-pos))
e1f00930
FEG
2046 (pop-to-buffer tracked-buffer)
2047 (switch-to-buffer-other-window shell-buffer))
2048 (when python-pdbtrack-tracked-buffer
2049 (with-current-buffer python-pdbtrack-tracked-buffer
2050 (set-marker overlay-arrow-position nil))
2051 (mapc #'(lambda (buffer)
2052 (ignore-errors (kill-buffer buffer)))
2053 python-pdbtrack-buffers-to-kill)
2054 (setq python-pdbtrack-tracked-buffer nil
2055 python-pdbtrack-buffers-to-kill nil)))))
45c138ac
FEG
2056 output)
2057
2058\f
2059;;; Symbol completion
2060
2061(defun python-completion-complete-at-point ()
2062 "Complete current symbol at point.
2063For this to work the best as possible you should call
2064`python-shell-send-buffer' from time to time so context in
2065inferior python process is updated properly."
2066 (interactive)
2067 (let ((process (python-shell-get-process)))
2068 (if (not process)
4289485a 2069 (error "Completion needs an inferior Python process running")
b71bfa9c 2070 (python-shell-completion--do-completion-at-point process))))
45c138ac 2071
6cad4c6e
FEG
2072(add-to-list 'debug-ignored-errors
2073 "^Completion needs an inferior Python process running.")
45c138ac
FEG
2074
2075\f
2076;;; Fill paragraph
2077
c2cb97ae
FEG
2078(defcustom python-fill-comment-function 'python-fill-comment
2079 "Function to fill comments.
2080This is the function used by `python-fill-paragraph-function' to
2081fill comments."
2082 :type 'symbol
2083 :group 'python
2084 :safe 'symbolp)
2085
2086(defcustom python-fill-string-function 'python-fill-string
2087 "Function to fill strings.
2088This is the function used by `python-fill-paragraph-function' to
2089fill strings."
2090 :type 'symbol
2091 :group 'python
2092 :safe 'symbolp)
2093
2094(defcustom python-fill-decorator-function 'python-fill-decorator
2095 "Function to fill decorators.
2096This is the function used by `python-fill-paragraph-function' to
2097fill decorators."
2098 :type 'symbol
2099 :group 'python
2100 :safe 'symbolp)
2101
2102(defcustom python-fill-paren-function 'python-fill-paren
2103 "Function to fill parens.
2104This is the function used by `python-fill-paragraph-function' to
2105fill parens."
2106 :type 'symbol
2107 :group 'python
2108 :safe 'symbolp)
2109
45c138ac
FEG
2110(defun python-fill-paragraph-function (&optional justify)
2111 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2112If any of the current line is in or at the end of a multi-line string,
2113fill the string or the paragraph of it that point is in, preserving
4e531f7a
FEG
2114the string's indentation.
2115Optional argument JUSTIFY defines if the paragraph should be justified."
45c138ac
FEG
2116 (interactive "P")
2117 (save-excursion
2118 (back-to-indentation)
2119 (cond
2120 ;; Comments
c2cb97ae
FEG
2121 ((funcall python-fill-comment-function justify))
2122 ;; Strings/Docstrings
45c138ac 2123 ((save-excursion (skip-chars-forward "\"'uUrR")
14a78495 2124 (python-info-ppss-context 'string))
c2cb97ae 2125 (funcall python-fill-string-function justify))
45c138ac
FEG
2126 ;; Decorators
2127 ((equal (char-after (save-excursion
2128 (back-to-indentation)
c2cb97ae
FEG
2129 (point-marker))) ?@)
2130 (funcall python-fill-decorator-function justify))
45c138ac 2131 ;; Parens
14a78495 2132 ((or (python-info-ppss-context 'paren)
45c138ac
FEG
2133 (looking-at (python-rx open-paren))
2134 (save-excursion
2135 (skip-syntax-forward "^(" (line-end-position))
2136 (looking-at (python-rx open-paren))))
c2cb97ae 2137 (funcall python-fill-paren-function justify))
45c138ac
FEG
2138 (t t))))
2139
c2cb97ae 2140(defun python-fill-comment (&optional justify)
053a6c72
FEG
2141 "Comment fill function for `python-fill-paragraph-function'.
2142JUSTIFY should be used (if applicable) as in `fill-paragraph'."
c2cb97ae
FEG
2143 (fill-comment-paragraph justify))
2144
2145(defun python-fill-string (&optional justify)
053a6c72
FEG
2146 "String fill function for `python-fill-paragraph-function'.
2147JUSTIFY should be used (if applicable) as in `fill-paragraph'."
c2cb97ae
FEG
2148 (let ((marker (point-marker))
2149 (string-start-marker
2150 (progn
2151 (skip-chars-forward "\"'uUrR")
2152 (goto-char (python-info-ppss-context 'string))
2153 (skip-chars-forward "\"'uUrR")
2154 (point-marker)))
2155 (reg-start (line-beginning-position))
2156 (string-end-marker
2157 (progn
2158 (while (python-info-ppss-context 'string)
2159 (goto-char (1+ (point-marker))))
2160 (skip-chars-backward "\"'")
2161 (point-marker)))
2162 (reg-end (line-end-position))
2163 (fill-paragraph-function))
2164 (save-restriction
2165 (narrow-to-region reg-start reg-end)
2166 (save-excursion
2167 (goto-char string-start-marker)
2168 (delete-region (point-marker) (progn
2169 (skip-syntax-forward "> ")
2170 (point-marker)))
2171 (goto-char string-end-marker)
2172 (delete-region (point-marker) (progn
2173 (skip-syntax-backward "> ")
2174 (point-marker)))
2175 (save-excursion
2176 (goto-char marker)
2177 (fill-paragraph justify))
2178 ;; If there is a newline in the docstring lets put triple
2179 ;; quote in it's own line to follow pep 8
2180 (when (save-excursion
2181 (re-search-backward "\n" string-start-marker t))
2182 (newline)
2183 (newline-and-indent))
2184 (fill-paragraph justify)))) t)
2185
2186(defun python-fill-decorator (&optional justify)
053a6c72
FEG
2187 "Decorator fill function for `python-fill-paragraph-function'.
2188JUSTIFY should be used (if applicable) as in `fill-paragraph'."
c2cb97ae
FEG
2189 t)
2190
2191(defun python-fill-paren (&optional justify)
053a6c72
FEG
2192 "Paren fill function for `python-fill-paragraph-function'.
2193JUSTIFY should be used (if applicable) as in `fill-paragraph'."
c2cb97ae
FEG
2194 (save-restriction
2195 (narrow-to-region (progn
2196 (while (python-info-ppss-context 'paren)
2197 (goto-char (1- (point-marker))))
2198 (point-marker)
2199 (line-beginning-position))
2200 (progn
2201 (when (not (python-info-ppss-context 'paren))
2202 (end-of-line)
2203 (when (not (python-info-ppss-context 'paren))
2204 (skip-syntax-backward "^)")))
2205 (while (python-info-ppss-context 'paren)
2206 (goto-char (1+ (point-marker))))
2207 (point-marker)))
2208 (let ((paragraph-start "\f\\|[ \t]*$")
2209 (paragraph-separate ",")
2210 (fill-paragraph-function))
2211 (goto-char (point-min))
2212 (fill-paragraph justify))
2213 (while (not (eobp))
2214 (forward-line 1)
2215 (python-indent-line)
2216 (goto-char (line-end-position)))) t)
2217
45c138ac 2218\f
e2803784
FEG
2219;;; Skeletons
2220
2221(defcustom python-skeleton-autoinsert nil
2222 "Non-nil means template skeletons will be automagically inserted.
2223This happens when pressing \"if<SPACE>\", for example, to prompt for
2224the if condition."
2225 :type 'boolean
0f55249e
FEG
2226 :group 'python
2227 :safe 'booleanp)
e2803784 2228
9ddf3c74
FEG
2229(define-obsolete-variable-alias
2230 'python-use-skeletons 'python-skeleton-autoinsert "24.2")
2231
e2803784
FEG
2232(defvar python-skeleton-available '()
2233 "Internal list of available skeletons.")
e2803784
FEG
2234
2235(define-abbrev-table 'python-mode-abbrev-table ()
2236 "Abbrev table for Python mode."
2237 :case-fixed t
2238 ;; Allow / inside abbrevs.
2239 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2240 ;; Only expand in code.
2241 :enable-function (lambda ()
e2803784 2242 (and
1d29cc7d 2243 (not (python-info-ppss-comment-or-string-p))
e2803784
FEG
2244 python-skeleton-autoinsert)))
2245
2246(defmacro python-skeleton-define (name doc &rest skel)
2247 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2248The skeleton will be bound to python-skeleton-NAME and will
2249be added to `python-mode-abbrev-table'."
25f09295 2250 (declare (indent 2))
e2803784 2251 (let* ((name (symbol-name name))
6cad4c6e 2252 (function-name (intern (concat "python-skeleton-" name))))
73ed6836 2253 `(progn
0e9e6c6a 2254 (define-abbrev python-mode-abbrev-table ,name "" ',function-name
d617c457 2255 :system t)
73ed6836
FEG
2256 (setq python-skeleton-available
2257 (cons ',function-name python-skeleton-available))
2258 (define-skeleton ,function-name
2259 ,(or doc
2260 (format "Insert %s statement." name))
2261 ,@skel))))
e2803784
FEG
2262
2263(defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
2264 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2265The skeleton will be bound to python-skeleton-NAME."
25f09295 2266 (declare (indent 2))
e2803784 2267 (let* ((name (symbol-name name))
6cad4c6e 2268 (function-name (intern (concat "python-skeleton--" name)))
e2803784
FEG
2269 (msg (format
2270 "Add '%s' clause? " name)))
2271 (when (not skel)
2272 (setq skel
2273 `(< ,(format "%s:" name) \n \n
2274 > _ \n)))
2275 `(define-skeleton ,function-name
2276 ,(or doc
2277 (format "Auxiliary skeleton for %s statement." name))
2278 nil
2279 (unless (y-or-n-p ,msg)
2280 (signal 'quit t))
2281 ,@skel)))
e2803784
FEG
2282
2283(python-define-auxiliary-skeleton else nil)
2284
2285(python-define-auxiliary-skeleton except nil)
2286
2287(python-define-auxiliary-skeleton finally nil)
2288
2289(python-skeleton-define if nil
2290 "Condition: "
2291 "if " str ":" \n
2292 _ \n
2293 ("other condition, %s: "
2294 <
2295 "elif " str ":" \n
2296 > _ \n nil)
2297 '(python-skeleton--else) | ^)
2298
2299(python-skeleton-define while nil
2300 "Condition: "
2301 "while " str ":" \n
2302 > _ \n
2303 '(python-skeleton--else) | ^)
2304
2305(python-skeleton-define for nil
2306 "Iteration spec: "
2307 "for " str ":" \n
2308 > _ \n
2309 '(python-skeleton--else) | ^)
2310
2311(python-skeleton-define try nil
2312 nil
2313 "try:" \n
2314 > _ \n
2315 ("Exception, %s: "
2316 <
2317 "except " str ":" \n
2318 > _ \n nil)
2319 resume:
2320 '(python-skeleton--except)
2321 '(python-skeleton--else)
2322 '(python-skeleton--finally) | ^)
2323
2324(python-skeleton-define def nil
2325 "Function name: "
2326 "def " str " (" ("Parameter, %s: "
2327 (unless (equal ?\( (char-before)) ", ")
6cad4c6e
FEG
2328 str) "):" \n
2329 "\"\"\"" - "\"\"\"" \n
2330 > _ \n)
e2803784
FEG
2331
2332(python-skeleton-define class nil
2333 "Class name: "
2334 "class " str " (" ("Inheritance, %s: "
6cad4c6e
FEG
2335 (unless (equal ?\( (char-before)) ", ")
2336 str)
e2803784
FEG
2337 & ")" | -2
2338 ":" \n
2339 "\"\"\"" - "\"\"\"" \n
2340 > _ \n)
2341
2342(defun python-skeleton-add-menu-items ()
2343 "Add menu items to Python->Skeletons menu."
2344 (let ((skeletons (sort python-skeleton-available 'string<))
2345 (items))
2346 (dolist (skeleton skeletons)
2347 (easy-menu-add-item
2348 nil '("Python" "Skeletons")
2349 `[,(format
2350 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
2351 ,skeleton t]))))
2352\f
046428d3
FEG
2353;;; FFAP
2354
0f55249e 2355(defcustom python-ffap-setup-code
046428d3
FEG
2356 "def __FFAP_get_module_path(module):
2357 try:
2358 import os
2359 path = __import__(module).__file__
2360 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2361 path = path[:-1]
2362 return path
2363 except:
2364 return ''"
0f55249e
FEG
2365 "Python code to get a module path."
2366 :type 'string
c4b155cb 2367 :group 'python)
046428d3 2368
0f55249e 2369(defcustom python-ffap-string-code
046428d3 2370 "__FFAP_get_module_path('''%s''')\n"
0f55249e
FEG
2371 "Python code used to get a string with the path of a module."
2372 :type 'string
c4b155cb 2373 :group 'python)
046428d3 2374
046428d3
FEG
2375(defun python-ffap-module-path (module)
2376 "Function for `ffap-alist' to return path for MODULE."
2377 (let ((process (or
2378 (and (eq major-mode 'inferior-python-mode)
2379 (get-buffer-process (current-buffer)))
2380 (python-shell-get-process))))
2381 (if (not process)
2382 nil
2383 (let ((module-file
9ce938be 2384 (python-shell-send-string-no-output
046428d3
FEG
2385 (format python-ffap-string-code module) process)))
2386 (when module-file
6cad4c6e 2387 (substring-no-properties module-file 1 -1))))))
046428d3
FEG
2388
2389(eval-after-load "ffap"
2390 '(progn
2391 (push '(python-mode . python-ffap-module-path) ffap-alist)
2392 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2393
046428d3 2394\f
8b3e0e76
FEG
2395;;; Code check
2396
0f55249e 2397(defcustom python-check-command
bba416bc 2398 "pyflakes"
0f55249e
FEG
2399 "Command used to check a Python file."
2400 :type 'string
c4b155cb 2401 :group 'python)
8b3e0e76 2402
bbd27e07
FEG
2403(defcustom python-check-buffer-name
2404 "*Python check: %s*"
2405 "Buffer name used for check commands."
2406 :type 'string
2407 :group 'python)
2408
8b3e0e76
FEG
2409(defvar python-check-custom-command nil
2410 "Internal use.")
2411
2412(defun python-check (command)
2413 "Check a Python file (default current buffer's file).
2414Runs COMMAND, a shell command, as if by `compile'. See
2415`python-check-command' for the default."
2416 (interactive
2417 (list (read-string "Check command: "
6cad4c6e
FEG
2418 (or python-check-custom-command
2419 (concat python-check-command " "
8b3e0e76
FEG
2420 (shell-quote-argument
2421 (or
2422 (let ((name (buffer-file-name)))
2423 (and name
2424 (file-name-nondirectory name)))
2425 "")))))))
2426 (setq python-check-custom-command command)
2427 (save-some-buffers (not compilation-ask-about-save) nil)
bba416bc
FEG
2428 (let ((process-environment (python-shell-calculate-process-environment))
2429 (exec-path (python-shell-calculate-exec-path)))
bbd27e07
FEG
2430 (compilation-start command nil
2431 (lambda (mode-name)
2432 (format python-check-buffer-name command)))))
8b3e0e76
FEG
2433
2434\f
45c138ac
FEG
2435;;; Eldoc
2436
0f55249e 2437(defcustom python-eldoc-setup-code
45c138ac
FEG
2438 "def __PYDOC_get_help(obj):
2439 try:
15cc40b8 2440 import inspect
9e662938
FEG
2441 if hasattr(obj, 'startswith'):
2442 obj = eval(obj, globals())
15cc40b8
FEG
2443 doc = inspect.getdoc(obj)
2444 if not doc and callable(obj):
2445 target = None
2446 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2447 target = obj.__init__
2448 objtype = 'class'
2449 else:
2450 target = obj
2451 objtype = 'def'
2452 if target:
2453 args = inspect.formatargspec(
2454 *inspect.getargspec(target)
2455 )
2456 name = obj.__name__
2457 doc = '{objtype} {name}{args}'.format(
2458 objtype=objtype, name=name, args=args
2459 )
2460 else:
2461 doc = doc.splitlines()[0]
45c138ac 2462 except:
9e662938
FEG
2463 doc = ''
2464 try:
2465 exec('print doc')
2466 except SyntaxError:
2467 print(doc)"
0f55249e
FEG
2468 "Python code to setup documentation retrieval."
2469 :type 'string
c4b155cb 2470 :group 'python)
45c138ac 2471
0f55249e 2472(defcustom python-eldoc-string-code
9e662938 2473 "__PYDOC_get_help('''%s''')\n"
0f55249e
FEG
2474 "Python code used to get a string with the documentation of an object."
2475 :type 'string
c4b155cb 2476 :group 'python)
45c138ac 2477
78334b43 2478(defun python-eldoc--get-doc-at-point (&optional force-input force-process)
d439cda5 2479 "Internal implementation to get documentation at point.
d583cbe6
FEG
2480If not FORCE-INPUT is passed then what
2481`python-info-current-symbol' returns will be used. If not
2482FORCE-PROCESS is passed what `python-shell-get-process' returns
2483is used."
78334b43 2484 (let ((process (or force-process (python-shell-get-process))))
45c138ac 2485 (if (not process)
d583cbe6
FEG
2486 (error "Eldoc needs an inferior Python process running")
2487 (let ((input (or force-input
2488 (python-info-current-symbol t))))
2489 (and input
2490 (python-shell-send-string-no-output
2491 (format python-eldoc-string-code input)
2492 process))))))
45c138ac 2493
78334b43
FEG
2494(defun python-eldoc-function ()
2495 "`eldoc-documentation-function' for Python.
2496For this to work the best as possible you should call
2497`python-shell-send-buffer' from time to time so context in
2498inferior python process is updated properly."
2499 (python-eldoc--get-doc-at-point))
2500
2501(defun python-eldoc-at-point (symbol)
2502 "Get help on SYMBOL using `help'.
2503Interactively, prompt for symbol."
6cad4c6e 2504 (interactive
d583cbe6 2505 (let ((symbol (python-info-current-symbol t))
6cad4c6e
FEG
2506 (enable-recursive-minibuffers t))
2507 (list (read-string (if symbol
2508 (format "Describe symbol (default %s): " symbol)
2509 "Describe symbol: ")
2510 nil nil symbol))))
d583cbe6
FEG
2511 (message (python-eldoc--get-doc-at-point symbol)))
2512
2513(add-to-list 'debug-ignored-errors
2514 "^Eldoc needs an inferior Python process running.")
78334b43 2515
45c138ac
FEG
2516\f
2517;;; Misc helpers
2518
fc2dc7df 2519(defun python-info-current-defun (&optional include-type)
45c138ac 2520 "Return name of surrounding function with Python compatible dotty syntax.
fc2dc7df 2521Optional argument INCLUDE-TYPE indicates to include the type of the defun.
45c138ac
FEG
2522This function is compatible to be used as
2523`add-log-current-defun-function' since it returns nil if point is
2524not inside a defun."
6b432853 2525 (let ((names '())
d583cbe6
FEG
2526 (starting-indentation)
2527 (starting-point)
0b7b2e51 2528 (first-run t))
45c138ac
FEG
2529 (save-restriction
2530 (widen)
2531 (save-excursion
d583cbe6
FEG
2532 (setq starting-point (point-marker))
2533 (setq starting-indentation (save-excursion
2534 (python-nav-beginning-of-statement)
2535 (current-indentation)))
8c6f9e60 2536 (end-of-line 1)
8c6f9e60 2537 (while (python-beginning-of-defun-function 1)
d583cbe6
FEG
2538 (when (or (< (current-indentation) starting-indentation)
2539 (and first-run
2540 (<
2541 starting-point
2542 (save-excursion
2543 (python-end-of-defun-function)
2544 (point-marker)))))
0b7b2e51 2545 (setq first-run nil)
d583cbe6 2546 (setq starting-indentation (current-indentation))
af5c1beb 2547 (looking-at python-nav-beginning-of-defun-regexp)
fc2dc7df
FEG
2548 (setq names (cons
2549 (if (not include-type)
2550 (match-string-no-properties 1)
2551 (mapconcat 'identity
2552 (split-string
2553 (match-string-no-properties 0)) " "))
2554 names))))))
45c138ac
FEG
2555 (when names
2556 (mapconcat (lambda (string) string) names "."))))
2557
d583cbe6
FEG
2558(defun python-info-current-symbol (&optional replace-self)
2559 "Return current symbol using dotty syntax.
2560With optional argument REPLACE-SELF convert \"self\" to current
2561parent defun name."
2562 (let ((name
2563 (and (not (python-info-ppss-comment-or-string-p))
2564 (with-syntax-table python-dotty-syntax-table
2565 (let ((sym (symbol-at-point)))
2566 (and sym
2567 (substring-no-properties (symbol-name sym))))))))
2568 (when name
2569 (if (not replace-self)
2570 name
2571 (let ((current-defun (python-info-current-defun)))
2572 (if (not current-defun)
2573 name
2574 (replace-regexp-in-string
2575 (python-rx line-start word-start "self" word-end ?.)
2576 (concat
2577 (mapconcat 'identity
2578 (butlast (split-string current-defun "\\."))
2579 ".") ".")
2580 name)))))))
2581
0a60bc10
FEG
2582(defsubst python-info-beginning-of-block-statement-p ()
2583 "Return non-nil if current statement opens a block."
2584 (save-excursion
2585 (python-nav-beginning-of-statement)
2586 (looking-at (python-rx block-start))))
2587
45c138ac 2588(defun python-info-closing-block ()
e2d8d479 2589 "Return the point of the block the current line closes."
45c138ac
FEG
2590 (let ((closing-word (save-excursion
2591 (back-to-indentation)
2592 (current-word)))
2593 (indentation (current-indentation)))
2594 (when (member closing-word python-indent-dedenters)
2595 (save-excursion
2596 (forward-line -1)
2597 (while (and (> (current-indentation) indentation)
2598 (not (bobp))
2599 (not (back-to-indentation))
2600 (forward-line -1)))
2601 (back-to-indentation)
2602 (cond
2603 ((not (equal indentation (current-indentation))) nil)
2604 ((string= closing-word "elif")
2605 (when (member (current-word) '("if" "elif"))
2606 (point-marker)))
2607 ((string= closing-word "else")
2608 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2609 (point-marker)))
2610 ((string= closing-word "except")
2611 (when (member (current-word) '("try"))
2612 (point-marker)))
2613 ((string= closing-word "finally")
2614 (when (member (current-word) '("except" "else"))
2615 (point-marker))))))))
2616
cd7ab092
FEG
2617(defun python-info-closing-block-message (&optional closing-block-point)
2618 "Message the contents of the block the current line closes.
2619With optional argument CLOSING-BLOCK-POINT use that instead of
2620recalculating it calling `python-info-closing-block'."
2621 (let ((point (or closing-block-point (python-info-closing-block))))
2622 (when point
2623 (save-restriction
2624 (widen)
2625 (message "Closes %s" (save-excursion
2626 (goto-char point)
2627 (back-to-indentation)
2628 (buffer-substring
2629 (point) (line-end-position))))))))
2630
0674d3fa 2631(defun python-info-line-ends-backslash-p (&optional line-number)
6cad4c6e 2632 "Return non-nil if current line ends with backslash.
0674d3fa 2633With optional argument LINE-NUMBER, check that line instead."
6cad4c6e
FEG
2634 (save-excursion
2635 (save-restriction
dc4f2e53 2636 (widen)
6cad4c6e
FEG
2637 (when line-number
2638 (goto-char line-number))
dc4f2e53
FEG
2639 (while (and (not (eobp))
2640 (goto-char (line-end-position))
2641 (python-info-ppss-context 'paren)
2642 (not (equal (char-before (point)) ?\\)))
2643 (forward-line 1))
2644 (when (equal (char-before) ?\\)
2645 (point-marker)))))
2646
48d1354e
PE
2647(defun python-info-beginning-of-backslash (&optional line-number)
2648 "Return the point where the backslashed line start.
4289485a 2649Optional argument LINE-NUMBER forces the line number to check against."
dc4f2e53
FEG
2650 (save-excursion
2651 (save-restriction
6cad4c6e 2652 (widen)
dc4f2e53
FEG
2653 (when line-number
2654 (goto-char line-number))
2655 (when (python-info-line-ends-backslash-p)
2656 (while (save-excursion
2657 (goto-char (line-beginning-position))
2658 (python-info-ppss-context 'paren))
2659 (forward-line -1))
2660 (back-to-indentation)
2661 (point-marker)))))
45c138ac
FEG
2662
2663(defun python-info-continuation-line-p ()
0674d3fa
FEG
2664 "Check if current line is continuation of another.
2665When current line is continuation of another return the point
2666where the continued line ends."
2667 (save-excursion
2668 (save-restriction
2669 (widen)
2670 (let* ((context-type (progn
2671 (back-to-indentation)
2672 (python-info-ppss-context-type)))
2673 (line-start (line-number-at-pos))
2674 (context-start (when context-type
2675 (python-info-ppss-context context-type))))
2676 (cond ((equal context-type 'paren)
2677 ;; Lines inside a paren are always a continuation line
2678 ;; (except the first one).
1d29cc7d
FEG
2679 (python-util-forward-comment -1)
2680 (point-marker))
2681 ((member context-type '(string comment))
0674d3fa
FEG
2682 ;; move forward an roll again
2683 (goto-char context-start)
2684 (python-util-forward-comment)
2685 (python-info-continuation-line-p))
2686 (t
1d29cc7d
FEG
2687 ;; Not within a paren, string or comment, the only way
2688 ;; we are dealing with a continuation line is that
2689 ;; previous line contains a backslash, and this can
2690 ;; only be the previous line from current
0674d3fa
FEG
2691 (back-to-indentation)
2692 (python-util-forward-comment -1)
0674d3fa
FEG
2693 (when (and (equal (1- line-start) (line-number-at-pos))
2694 (python-info-line-ends-backslash-p))
2695 (point-marker))))))))
45c138ac
FEG
2696
2697(defun python-info-block-continuation-line-p ()
2698 "Return non-nil if current line is a continuation of a block."
2699 (save-excursion
0674d3fa
FEG
2700 (when (python-info-continuation-line-p)
2701 (forward-line -1)
2702 (back-to-indentation)
2703 (when (looking-at (python-rx block-start))
2704 (point-marker)))))
45c138ac
FEG
2705
2706(defun python-info-assignment-continuation-line-p ()
0674d3fa
FEG
2707 "Check if current line is a continuation of an assignment.
2708When current line is continuation of another with an assignment
2709return the point of the first non-blank character after the
2710operator."
45c138ac 2711 (save-excursion
0674d3fa
FEG
2712 (when (python-info-continuation-line-p)
2713 (forward-line -1)
2714 (back-to-indentation)
2715 (when (and (not (looking-at (python-rx block-start)))
45c138ac
FEG
2716 (and (re-search-forward (python-rx not-simple-operator
2717 assignment-operator
2718 not-simple-operator)
2719 (line-end-position) t)
1d29cc7d 2720 (not (python-info-ppss-context-type))))
0674d3fa
FEG
2721 (skip-syntax-forward "\s")
2722 (point-marker)))))
45c138ac 2723
14a78495
FEG
2724(defun python-info-ppss-context (type &optional syntax-ppss)
2725 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
1d29cc7d 2726TYPE can be `comment', `string' or `paren'. It returns the start
14a78495
FEG
2727character address of the specified TYPE."
2728 (let ((ppss (or syntax-ppss (syntax-ppss))))
2729 (case type
1d29cc7d 2730 (comment
14a78495
FEG
2731 (and (nth 4 ppss)
2732 (nth 8 ppss)))
1d29cc7d 2733 (string
0a60bc10
FEG
2734 (and (not (nth 4 ppss))
2735 (nth 8 ppss)))
1d29cc7d 2736 (paren
14a78495
FEG
2737 (nth 1 ppss))
2738 (t nil))))
2739
85655287
FEG
2740(defun python-info-ppss-context-type (&optional syntax-ppss)
2741 "Return the context type using SYNTAX-PPSS.
1d29cc7d 2742The type returned can be `comment', `string' or `paren'."
85655287
FEG
2743 (let ((ppss (or syntax-ppss (syntax-ppss))))
2744 (cond
1d29cc7d
FEG
2745 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
2746 ((nth 1 ppss) 'paren))))
85655287 2747
0a60bc10
FEG
2748(defsubst python-info-ppss-comment-or-string-p ()
2749 "Return non-nil if point is inside 'comment or 'string."
1d29cc7d 2750 (nth 8 (syntax-ppss)))
0a60bc10 2751
8c6f9e60 2752(defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
4289485a
FEG
2753 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
2754 (and (not (python-info-ppss-context-type (or syntax-ppss (syntax-ppss))))
8c6f9e60
FEG
2755 (save-excursion
2756 (beginning-of-line 1)
2757 (looking-at python-nav-beginning-of-defun-regexp))))
2758
032d23ab
FEG
2759(defun python-info-current-line-comment-p ()
2760 "Check if current line is a comment line."
2761 (char-equal (or (char-after (+ (point) (current-indentation))) ?_) ?#))
2762
2763(defun python-info-current-line-empty-p ()
2764 "Check if current line is empty, ignoring whitespace."
2765 (save-excursion
2766 (beginning-of-line 1)
2767 (looking-at
2768 (python-rx line-start (* whitespace)
2769 (group (* not-newline))
2770 (* whitespace) line-end))
2771 (string-equal "" (match-string-no-properties 1))))
2772
45c138ac 2773\f
c942de99
FEG
2774;;; Utility functions
2775
c942de99
FEG
2776(defun python-util-position (item seq)
2777 "Find the first occurrence of ITEM in SEQ.
2778Return the index of the matching item, or nil if not found."
2779 (let ((member-result (member item seq)))
2780 (when member-result
2781 (- (length seq) (length member-result)))))
2782
d2190c57 2783;; Stolen from org-mode
fbc39529 2784(defun python-util-clone-local-variables (from-buffer &optional regexp)
d2190c57
FEG
2785 "Clone local variables from FROM-BUFFER.
2786Optional argument REGEXP selects variables to clone and defaults
2787to \"^python-\"."
2788 (mapc
2789 (lambda (pair)
2790 (and (symbolp (car pair))
2791 (string-match (or regexp "^python-")
2792 (symbol-name (car pair)))
6cad4c6e
FEG
2793 (set (make-local-variable (car pair))
2794 (cdr pair))))
d2190c57
FEG
2795 (buffer-local-variables from-buffer)))
2796
0674d3fa 2797(defun python-util-forward-comment (&optional direction)
4289485a
FEG
2798 "Python mode specific version of `forward-comment'.
2799Optional argument DIRECTION defines the direction to move to."
0674d3fa
FEG
2800 (let ((comment-start (python-info-ppss-context 'comment))
2801 (factor (if (< (or direction 0) 0)
2802 -99999
2803 99999)))
2804 (when comment-start
2805 (goto-char comment-start))
2806 (forward-comment factor)))
2807
c942de99 2808\f
45c138ac 2809;;;###autoload
68f12411 2810(define-derived-mode python-mode prog-mode "Python"
e2d8d479
FEG
2811 "Major mode for editing Python files.
2812
2813\\{python-mode-map}
2814Entry to this mode calls the value of `python-mode-hook'
2815if that value is non-nil."
45c138ac
FEG
2816 (set (make-local-variable 'tab-width) 8)
2817 (set (make-local-variable 'indent-tabs-mode) nil)
2818
2819 (set (make-local-variable 'comment-start) "# ")
2820 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2821
2822 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2823 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2824
032d23ab
FEG
2825 (set (make-local-variable 'forward-sexp-function)
2826 'python-nav-forward-sexp-function)
2827
45c138ac 2828 (set (make-local-variable 'font-lock-defaults)
aeadd9a4
FEG
2829 '(python-font-lock-keywords nil nil nil nil))
2830
2831 (set (make-local-variable 'syntax-propertize-function)
2832 python-syntax-propertize-function)
45c138ac 2833
6cad4c6e
FEG
2834 (set (make-local-variable 'indent-line-function)
2835 #'python-indent-line-function)
45c138ac
FEG
2836 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2837
2838 (set (make-local-variable 'paragraph-start) "\\s-*$")
6cad4c6e
FEG
2839 (set (make-local-variable 'fill-paragraph-function)
2840 'python-fill-paragraph-function)
45c138ac
FEG
2841
2842 (set (make-local-variable 'beginning-of-defun-function)
2843 #'python-beginning-of-defun-function)
2844 (set (make-local-variable 'end-of-defun-function)
2845 #'python-end-of-defun-function)
2846
2847 (add-hook 'completion-at-point-functions
2848 'python-completion-complete-at-point nil 'local)
2849
5eae76ae
FEG
2850 (add-hook 'post-self-insert-hook
2851 'python-indent-post-self-insert-function nil 'local)
2852
758e556a
FEG
2853 (set (make-local-variable 'imenu-extract-index-name-function)
2854 #'python-info-current-defun)
fc2dc7df 2855
45c138ac
FEG
2856 (set (make-local-variable 'add-log-current-defun-function)
2857 #'python-info-current-defun)
2858
c6d3df36
FEG
2859 (add-hook 'which-func-functions #'python-info-current-defun nil t)
2860
e2803784
FEG
2861 (set (make-local-variable 'skeleton-further-elements)
2862 '((abbrev-mode nil)
2863 (< '(backward-delete-char-untabify (min python-indent-offset
6cad4c6e
FEG
2864 (current-column))))
2865 (^ '(- (1+ (current-indentation))))))
e2803784 2866
45c138ac
FEG
2867 (set (make-local-variable 'eldoc-documentation-function)
2868 #'python-eldoc-function)
2869
2870 (add-to-list 'hs-special-modes-alist
6cad4c6e 2871 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
45c138ac
FEG
2872 ,(lambda (arg)
2873 (python-end-of-defun-function)) nil))
2874
82c2b0de
FEG
2875 (set (make-local-variable 'mode-require-final-newline) t)
2876
45c138ac
FEG
2877 (set (make-local-variable 'outline-regexp)
2878 (python-rx (* space) block-start))
2879 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2880 (set (make-local-variable 'outline-level)
2881 #'(lambda ()
2882 "`outline-level' function for Python mode."
2883 (1+ (/ (current-indentation) python-indent-offset))))
2884
e2803784
FEG
2885 (python-skeleton-add-menu-items)
2886
45c138ac
FEG
2887 (when python-indent-guess-indent-offset
2888 (python-indent-guess-indent-offset)))
2889
2890
2891(provide 'python)
d617c457
FEG
2892
2893;; Local Variables:
2894;; coding: utf-8
2895;; indent-tabs-mode: nil
2896;; End:
2897
45c138ac 2898;;; python.el ends here