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