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