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