* progmodes/python.el (python-shell-send-region): Add blank lines
[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
2012 (concat
2013 (let ((line-num (line-number-at-pos start)))
2014 ;; When sending a region, add blank lines for non sent code so
2015 ;; backtraces remain correct.
2016 (make-string (1- line-num) ?\n))
2017 (buffer-substring start end))
2018 nil t))
2019
2020 (defun python-shell-send-buffer (&optional arg)
2021 "Send the entire buffer to inferior Python process.
2022 With prefix ARG allow execution of code inside blocks delimited
2023 by \"if __name__== '__main__':\""
2024 (interactive "P")
2025 (save-restriction
2026 (widen)
2027 (let ((str (buffer-substring (point-min) (point-max))))
2028 (and
2029 (not arg)
2030 (setq str (replace-regexp-in-string
2031 (python-rx if-name-main)
2032 "if __name__ == '__main__ ':" str)))
2033 (python-shell-send-string str))))
2034
2035 (defun python-shell-send-defun (arg)
2036 "Send the current defun to inferior Python process.
2037 When argument ARG is non-nil do not include decorators."
2038 (interactive "P")
2039 (save-excursion
2040 (python-shell-send-region
2041 (progn
2042 (end-of-line 1)
2043 (while (and (or (python-nav-beginning-of-defun)
2044 (beginning-of-line 1))
2045 (> (current-indentation) 0)))
2046 (when (not arg)
2047 (while (and (forward-line -1)
2048 (looking-at (python-rx decorator))))
2049 (forward-line 1))
2050 (point-marker))
2051 (progn
2052 (or (python-nav-end-of-defun)
2053 (end-of-line 1))
2054 (point-marker)))))
2055
2056 (defun python-shell-send-file (file-name &optional process temp-file-name)
2057 "Send FILE-NAME to inferior Python PROCESS.
2058 If TEMP-FILE-NAME is passed then that file is used for processing
2059 instead, while internally the shell will continue to use
2060 FILE-NAME."
2061 (interactive "fFile to send: ")
2062 (let* ((process (or process (python-shell-get-or-create-process)))
2063 (temp-file-name (when temp-file-name
2064 (expand-file-name
2065 (or (file-remote-p temp-file-name 'localname)
2066 temp-file-name))))
2067 (file-name (or (when file-name
2068 (expand-file-name
2069 (or (file-remote-p file-name 'localname)
2070 file-name)))
2071 temp-file-name)))
2072 (when (not file-name)
2073 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2074 (python-shell-send-string
2075 (format
2076 (concat "__pyfile = open('''%s''');"
2077 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2078 "__pyfile.close()")
2079 (or temp-file-name file-name) file-name)
2080 process)))
2081
2082 (defun python-shell-switch-to-shell ()
2083 "Switch to inferior Python process buffer."
2084 (interactive)
2085 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
2086
2087 (defun python-shell-send-setup-code ()
2088 "Send all setup code for shell.
2089 This function takes the list of setup code to send from the
2090 `python-shell-setup-codes' list."
2091 (let ((process (get-buffer-process (current-buffer))))
2092 (dolist (code python-shell-setup-codes)
2093 (when code
2094 (message "Sent %s" code)
2095 (python-shell-send-string
2096 (symbol-value code) process)))))
2097
2098 (add-hook 'inferior-python-mode-hook
2099 #'python-shell-send-setup-code)
2100
2101 \f
2102 ;;; Shell completion
2103
2104 (defcustom python-shell-completion-setup-code
2105 "try:
2106 import readline
2107 except ImportError:
2108 def __COMPLETER_all_completions(text): []
2109 else:
2110 import rlcompleter
2111 readline.set_completer(rlcompleter.Completer().complete)
2112 def __COMPLETER_all_completions(text):
2113 import sys
2114 completions = []
2115 try:
2116 i = 0
2117 while True:
2118 res = readline.get_completer()(text, i)
2119 if not res: break
2120 i += 1
2121 completions.append(res)
2122 except NameError:
2123 pass
2124 return completions"
2125 "Code used to setup completion in inferior Python processes."
2126 :type 'string
2127 :group 'python)
2128
2129 (defcustom python-shell-completion-string-code
2130 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2131 "Python code used to get a string of completions separated by semicolons."
2132 :type 'string
2133 :group 'python)
2134
2135 (defcustom python-shell-completion-module-string-code ""
2136 "Python code used to get completions separated by semicolons for imports.
2137
2138 For IPython v0.11, add the following line to
2139 `python-shell-completion-setup-code':
2140
2141 from IPython.core.completerlib import module_completion
2142
2143 and use the following as the value of this variable:
2144
2145 ';'.join(module_completion('''%s'''))\n"
2146 :type 'string
2147 :group 'python)
2148
2149 (defcustom python-shell-completion-pdb-string-code
2150 "';'.join(globals().keys() + locals().keys())"
2151 "Python code used to get completions separated by semicolons for [i]pdb."
2152 :type 'string
2153 :group 'python)
2154
2155 (defun python-shell-completion-get-completions (process line input)
2156 "Do completion at point for PROCESS.
2157 LINE is used to detect the context on how to complete given
2158 INPUT."
2159 (let* ((prompt
2160 ;; Get the last prompt for the inferior process
2161 ;; buffer. This is used for the completion code selection
2162 ;; heuristic.
2163 (with-current-buffer (process-buffer process)
2164 (buffer-substring-no-properties
2165 (overlay-start comint-last-prompt-overlay)
2166 (overlay-end comint-last-prompt-overlay))))
2167 (completion-context
2168 ;; Check whether a prompt matches a pdb string, an import
2169 ;; statement or just the standard prompt and use the
2170 ;; correct python-shell-completion-*-code string
2171 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
2172 (string-match
2173 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2174 'pdb)
2175 ((and (>
2176 (length python-shell-completion-module-string-code) 0)
2177 (string-match
2178 (concat "^" python-shell-prompt-regexp) prompt)
2179 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line))
2180 'import)
2181 ((string-match
2182 (concat "^" python-shell-prompt-regexp) prompt)
2183 'default)
2184 (t nil)))
2185 (completion-code
2186 (pcase completion-context
2187 (`pdb python-shell-completion-pdb-string-code)
2188 (`import python-shell-completion-module-string-code)
2189 (`default python-shell-completion-string-code)
2190 (_ nil)))
2191 (input
2192 (if (eq completion-context 'import)
2193 (replace-regexp-in-string "^[ \t]+" "" line)
2194 input)))
2195 (and completion-code
2196 (> (length input) 0)
2197 (with-current-buffer (process-buffer process)
2198 (let ((completions (python-shell-send-string-no-output
2199 (format completion-code input) process)))
2200 (and (> (length completions) 2)
2201 (split-string completions
2202 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
2203
2204 (defun python-shell-completion-complete-at-point (&optional process)
2205 "Perform completion at point in inferior Python.
2206 Optional argument PROCESS forces completions to be retrieved
2207 using that one instead of current buffer's process."
2208 (setq process (or process (get-buffer-process (current-buffer))))
2209 (let* ((start
2210 (save-excursion
2211 (with-syntax-table python-dotty-syntax-table
2212 (let* ((paren-depth (car (syntax-ppss)))
2213 (syntax-string "w_")
2214 (syntax-list (string-to-syntax syntax-string)))
2215 ;; Stop scanning for the beginning of the completion
2216 ;; subject after the char before point matches a
2217 ;; delimiter
2218 (while (member
2219 (car (syntax-after (1- (point)))) syntax-list)
2220 (skip-syntax-backward syntax-string)
2221 (when (or (equal (char-before) ?\))
2222 (equal (char-before) ?\"))
2223 (forward-char -1))
2224 (while (or
2225 ;; honor initial paren depth
2226 (> (car (syntax-ppss)) paren-depth)
2227 (python-syntax-context 'string))
2228 (forward-char -1)))
2229 (point)))))
2230 (end (point)))
2231 (list start end
2232 (completion-table-dynamic
2233 (apply-partially
2234 #'python-shell-completion-get-completions
2235 process (buffer-substring-no-properties
2236 (line-beginning-position) end))))))
2237
2238 (defun python-shell-completion-complete-or-indent ()
2239 "Complete or indent depending on the context.
2240 If content before pointer is all whitespace indent. If not try
2241 to complete."
2242 (interactive)
2243 (if (string-match "^[[:space:]]*$"
2244 (buffer-substring (comint-line-beginning-position)
2245 (point-marker)))
2246 (indent-for-tab-command)
2247 (completion-at-point)))
2248
2249 \f
2250 ;;; PDB Track integration
2251
2252 (defcustom python-pdbtrack-activate t
2253 "Non-nil makes python shell enable pdbtracking."
2254 :type 'boolean
2255 :group 'python
2256 :safe 'booleanp)
2257
2258 (defcustom python-pdbtrack-stacktrace-info-regexp
2259 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2260 "Regular Expression matching stacktrace information.
2261 Used to extract the current line and module being inspected."
2262 :type 'string
2263 :group 'python
2264 :safe 'stringp)
2265
2266 (defvar python-pdbtrack-tracked-buffer nil
2267 "Variable containing the value of the current tracked buffer.
2268 Never set this variable directly, use
2269 `python-pdbtrack-set-tracked-buffer' instead.")
2270
2271 (defvar python-pdbtrack-buffers-to-kill nil
2272 "List of buffers to be deleted after tracking finishes.")
2273
2274 (defun python-pdbtrack-set-tracked-buffer (file-name)
2275 "Set the buffer for FILE-NAME as the tracked buffer.
2276 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2277 Returns the tracked buffer."
2278 (let ((file-buffer (get-file-buffer file-name)))
2279 (if file-buffer
2280 (setq python-pdbtrack-tracked-buffer file-buffer)
2281 (setq file-buffer (find-file-noselect file-name))
2282 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
2283 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
2284 file-buffer))
2285
2286 (defun python-pdbtrack-comint-output-filter-function (output)
2287 "Move overlay arrow to current pdb line in tracked buffer.
2288 Argument OUTPUT is a string with the output from the comint process."
2289 (when (and python-pdbtrack-activate (not (string= output "")))
2290 (let* ((full-output (ansi-color-filter-apply
2291 (buffer-substring comint-last-input-end (point-max))))
2292 (line-number)
2293 (file-name
2294 (with-temp-buffer
2295 (insert full-output)
2296 (goto-char (point-min))
2297 ;; OK, this sucked but now it became a cool hack. The
2298 ;; stacktrace information normally is on the first line
2299 ;; but in some cases (like when doing a step-in) it is
2300 ;; on the second.
2301 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp)
2302 (and
2303 (forward-line)
2304 (looking-at python-pdbtrack-stacktrace-info-regexp)))
2305 (setq line-number (string-to-number
2306 (match-string-no-properties 2)))
2307 (match-string-no-properties 1)))))
2308 (if (and file-name line-number)
2309 (let* ((tracked-buffer
2310 (python-pdbtrack-set-tracked-buffer file-name))
2311 (shell-buffer (current-buffer))
2312 (tracked-buffer-window (get-buffer-window tracked-buffer))
2313 (tracked-buffer-line-pos))
2314 (with-current-buffer tracked-buffer
2315 (set (make-local-variable 'overlay-arrow-string) "=>")
2316 (set (make-local-variable 'overlay-arrow-position) (make-marker))
2317 (setq tracked-buffer-line-pos (progn
2318 (goto-char (point-min))
2319 (forward-line (1- line-number))
2320 (point-marker)))
2321 (when tracked-buffer-window
2322 (set-window-point
2323 tracked-buffer-window tracked-buffer-line-pos))
2324 (set-marker overlay-arrow-position tracked-buffer-line-pos))
2325 (pop-to-buffer tracked-buffer)
2326 (switch-to-buffer-other-window shell-buffer))
2327 (when python-pdbtrack-tracked-buffer
2328 (with-current-buffer python-pdbtrack-tracked-buffer
2329 (set-marker overlay-arrow-position nil))
2330 (mapc #'(lambda (buffer)
2331 (ignore-errors (kill-buffer buffer)))
2332 python-pdbtrack-buffers-to-kill)
2333 (setq python-pdbtrack-tracked-buffer nil
2334 python-pdbtrack-buffers-to-kill nil)))))
2335 output)
2336
2337 \f
2338 ;;; Symbol completion
2339
2340 (defun python-completion-complete-at-point ()
2341 "Complete current symbol at point.
2342 For this to work the best as possible you should call
2343 `python-shell-send-buffer' from time to time so context in
2344 inferior python process is updated properly."
2345 (let ((process (python-shell-get-process)))
2346 (if (not process)
2347 (error "Completion needs an inferior Python process running")
2348 (python-shell-completion-complete-at-point process))))
2349
2350 (add-to-list 'debug-ignored-errors
2351 "^Completion needs an inferior Python process running.")
2352
2353 \f
2354 ;;; Fill paragraph
2355
2356 (defcustom python-fill-comment-function 'python-fill-comment
2357 "Function to fill comments.
2358 This is the function used by `python-fill-paragraph' to
2359 fill comments."
2360 :type 'symbol
2361 :group 'python)
2362
2363 (defcustom python-fill-string-function 'python-fill-string
2364 "Function to fill strings.
2365 This is the function used by `python-fill-paragraph' to
2366 fill strings."
2367 :type 'symbol
2368 :group 'python)
2369
2370 (defcustom python-fill-decorator-function 'python-fill-decorator
2371 "Function to fill decorators.
2372 This is the function used by `python-fill-paragraph' to
2373 fill decorators."
2374 :type 'symbol
2375 :group 'python)
2376
2377 (defcustom python-fill-paren-function 'python-fill-paren
2378 "Function to fill parens.
2379 This is the function used by `python-fill-paragraph' to
2380 fill parens."
2381 :type 'symbol
2382 :group 'python)
2383
2384 (defcustom python-fill-docstring-style 'pep-257
2385 "Style used to fill docstrings.
2386 This affects `python-fill-string' behavior with regards to
2387 triple quotes positioning.
2388
2389 Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2390 SYMMETRIC, and NIL. A value of NIL won't care about quotes
2391 position and will treat docstrings a normal string, any other
2392 value may result in one of the following docstring styles:
2393
2394 DJANGO:
2395
2396 \"\"\"
2397 Process foo, return bar.
2398 \"\"\"
2399
2400 \"\"\"
2401 Process foo, return bar.
2402
2403 If processing fails throw ProcessingError.
2404 \"\"\"
2405
2406 ONETWO:
2407
2408 \"\"\"Process foo, return bar.\"\"\"
2409
2410 \"\"\"
2411 Process foo, return bar.
2412
2413 If processing fails throw ProcessingError.
2414
2415 \"\"\"
2416
2417 PEP-257:
2418
2419 \"\"\"Process foo, return bar.\"\"\"
2420
2421 \"\"\"Process foo, return bar.
2422
2423 If processing fails throw ProcessingError.
2424
2425 \"\"\"
2426
2427 PEP-257-NN:
2428
2429 \"\"\"Process foo, return bar.\"\"\"
2430
2431 \"\"\"Process foo, return bar.
2432
2433 If processing fails throw ProcessingError.
2434 \"\"\"
2435
2436 SYMMETRIC:
2437
2438 \"\"\"Process foo, return bar.\"\"\"
2439
2440 \"\"\"
2441 Process foo, return bar.
2442
2443 If processing fails throw ProcessingError.
2444 \"\"\""
2445 :type '(choice
2446 (const :tag "Don't format docstrings" nil)
2447 (const :tag "Django's coding standards style." django)
2448 (const :tag "One newline and start and Two at end style." onetwo)
2449 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
2450 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
2451 (const :tag "Symmetric style." symmetric))
2452 :group 'python
2453 :safe (lambda (val)
2454 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
2455
2456 (defun python-fill-paragraph (&optional justify)
2457 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2458 If any of the current line is in or at the end of a multi-line string,
2459 fill the string or the paragraph of it that point is in, preserving
2460 the string's indentation.
2461 Optional argument JUSTIFY defines if the paragraph should be justified."
2462 (interactive "P")
2463 (save-excursion
2464 (cond
2465 ;; Comments
2466 ((python-syntax-context 'comment)
2467 (funcall python-fill-comment-function justify))
2468 ;; Strings/Docstrings
2469 ((save-excursion (or (python-syntax-context 'string)
2470 (equal (string-to-syntax "|")
2471 (syntax-after (point)))))
2472 (funcall python-fill-string-function justify))
2473 ;; Decorators
2474 ((equal (char-after (save-excursion
2475 (python-nav-beginning-of-statement))) ?@)
2476 (funcall python-fill-decorator-function justify))
2477 ;; Parens
2478 ((or (python-syntax-context 'paren)
2479 (looking-at (python-rx open-paren))
2480 (save-excursion
2481 (skip-syntax-forward "^(" (line-end-position))
2482 (looking-at (python-rx open-paren))))
2483 (funcall python-fill-paren-function justify))
2484 (t t))))
2485
2486 (defun python-fill-comment (&optional justify)
2487 "Comment fill function for `python-fill-paragraph'.
2488 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2489 (fill-comment-paragraph justify))
2490
2491 (defun python-fill-string (&optional justify)
2492 "String fill function for `python-fill-paragraph'.
2493 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2494 (let* ((marker (point-marker))
2495 (str-start-pos
2496 (set-marker
2497 (make-marker)
2498 (or (python-syntax-context 'string)
2499 (and (equal (string-to-syntax "|")
2500 (syntax-after (point)))
2501 (point)))))
2502 (num-quotes (python-syntax-count-quotes
2503 (char-after str-start-pos) str-start-pos))
2504 (str-end-pos
2505 (save-excursion
2506 (goto-char (+ str-start-pos num-quotes))
2507 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
2508 (goto-char (point-max)))
2509 (point-marker)))
2510 (multi-line-p
2511 ;; Docstring styles may vary for oneliners and multi-liners.
2512 (> (count-matches "\n" str-start-pos str-end-pos) 0))
2513 (delimiters-style
2514 (pcase python-fill-docstring-style
2515 ;; delimiters-style is a cons cell with the form
2516 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2517 ;; is NIL means to not add any newlines for start or end
2518 ;; of docstring. See `python-fill-docstring-style' for a
2519 ;; graphic idea of each style.
2520 (`django (cons 1 1))
2521 (`onetwo (and multi-line-p (cons 1 2)))
2522 (`pep-257 (and multi-line-p (cons nil 2)))
2523 (`pep-257-nn (and multi-line-p (cons nil 1)))
2524 (`symmetric (and multi-line-p (cons 1 1)))))
2525 (docstring-p (save-excursion
2526 ;; Consider docstrings those strings which
2527 ;; start on a line by themselves.
2528 (python-nav-beginning-of-statement)
2529 (and (= (point) str-start-pos))))
2530 (fill-paragraph-function))
2531 (save-restriction
2532 (narrow-to-region str-start-pos str-end-pos)
2533 (fill-paragraph justify))
2534 (save-excursion
2535 (when (and docstring-p python-fill-docstring-style)
2536 ;; Add the number of newlines indicated by the selected style
2537 ;; at the start of the docstring.
2538 (goto-char (+ str-start-pos num-quotes))
2539 (delete-region (point) (progn
2540 (skip-syntax-forward "> ")
2541 (point)))
2542 (and (car delimiters-style)
2543 (or (newline (car delimiters-style)) t)
2544 ;; Indent only if a newline is added.
2545 (indent-according-to-mode))
2546 ;; Add the number of newlines indicated by the selected style
2547 ;; at the end of the docstring.
2548 (goto-char (if (not (= str-end-pos (point-max)))
2549 (- str-end-pos num-quotes)
2550 str-end-pos))
2551 (delete-region (point) (progn
2552 (skip-syntax-backward "> ")
2553 (point)))
2554 (and (cdr delimiters-style)
2555 ;; Add newlines only if string ends.
2556 (not (= str-end-pos (point-max)))
2557 (or (newline (cdr delimiters-style)) t)
2558 ;; Again indent only if a newline is added.
2559 (indent-according-to-mode))))) t)
2560
2561 (defun python-fill-decorator (&optional justify)
2562 "Decorator fill function for `python-fill-paragraph'.
2563 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2564 t)
2565
2566 (defun python-fill-paren (&optional justify)
2567 "Paren fill function for `python-fill-paragraph'.
2568 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2569 (save-restriction
2570 (narrow-to-region (progn
2571 (while (python-syntax-context 'paren)
2572 (goto-char (1- (point-marker))))
2573 (point-marker)
2574 (line-beginning-position))
2575 (progn
2576 (when (not (python-syntax-context 'paren))
2577 (end-of-line)
2578 (when (not (python-syntax-context 'paren))
2579 (skip-syntax-backward "^)")))
2580 (while (python-syntax-context 'paren)
2581 (goto-char (1+ (point-marker))))
2582 (point-marker)))
2583 (let ((paragraph-start "\f\\|[ \t]*$")
2584 (paragraph-separate ",")
2585 (fill-paragraph-function))
2586 (goto-char (point-min))
2587 (fill-paragraph justify))
2588 (while (not (eobp))
2589 (forward-line 1)
2590 (python-indent-line)
2591 (goto-char (line-end-position)))) t)
2592
2593 \f
2594 ;;; Skeletons
2595
2596 (defcustom python-skeleton-autoinsert nil
2597 "Non-nil means template skeletons will be automagically inserted.
2598 This happens when pressing \"if<SPACE>\", for example, to prompt for
2599 the if condition."
2600 :type 'boolean
2601 :group 'python
2602 :safe 'booleanp)
2603
2604 (define-obsolete-variable-alias
2605 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
2606
2607 (defvar python-skeleton-available '()
2608 "Internal list of available skeletons.")
2609
2610 (define-abbrev-table 'python-mode-abbrev-table ()
2611 "Abbrev table for Python mode."
2612 :case-fixed t
2613 ;; Allow / inside abbrevs.
2614 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2615 ;; Only expand in code.
2616 :enable-function (lambda ()
2617 (and
2618 (not (python-syntax-comment-or-string-p))
2619 python-skeleton-autoinsert)))
2620
2621 (defmacro python-skeleton-define (name doc &rest skel)
2622 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2623 The skeleton will be bound to python-skeleton-NAME and will
2624 be added to `python-mode-abbrev-table'."
2625 (declare (indent 2))
2626 (let* ((name (symbol-name name))
2627 (function-name (intern (concat "python-skeleton-" name))))
2628 `(progn
2629 (define-abbrev python-mode-abbrev-table ,name "" ',function-name
2630 :system t)
2631 (setq python-skeleton-available
2632 (cons ',function-name python-skeleton-available))
2633 (define-skeleton ,function-name
2634 ,(or doc
2635 (format "Insert %s statement." name))
2636 ,@skel))))
2637
2638 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
2639 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2640 The skeleton will be bound to python-skeleton-NAME."
2641 (declare (indent 2))
2642 (let* ((name (symbol-name name))
2643 (function-name (intern (concat "python-skeleton--" name)))
2644 (msg (format
2645 "Add '%s' clause? " name)))
2646 (when (not skel)
2647 (setq skel
2648 `(< ,(format "%s:" name) \n \n
2649 > _ \n)))
2650 `(define-skeleton ,function-name
2651 ,(or doc
2652 (format "Auxiliary skeleton for %s statement." name))
2653 nil
2654 (unless (y-or-n-p ,msg)
2655 (signal 'quit t))
2656 ,@skel)))
2657
2658 (python-define-auxiliary-skeleton else nil)
2659
2660 (python-define-auxiliary-skeleton except nil)
2661
2662 (python-define-auxiliary-skeleton finally nil)
2663
2664 (python-skeleton-define if nil
2665 "Condition: "
2666 "if " str ":" \n
2667 _ \n
2668 ("other condition, %s: "
2669 <
2670 "elif " str ":" \n
2671 > _ \n nil)
2672 '(python-skeleton--else) | ^)
2673
2674 (python-skeleton-define while nil
2675 "Condition: "
2676 "while " str ":" \n
2677 > _ \n
2678 '(python-skeleton--else) | ^)
2679
2680 (python-skeleton-define for nil
2681 "Iteration spec: "
2682 "for " str ":" \n
2683 > _ \n
2684 '(python-skeleton--else) | ^)
2685
2686 (python-skeleton-define try nil
2687 nil
2688 "try:" \n
2689 > _ \n
2690 ("Exception, %s: "
2691 <
2692 "except " str ":" \n
2693 > _ \n nil)
2694 resume:
2695 '(python-skeleton--except)
2696 '(python-skeleton--else)
2697 '(python-skeleton--finally) | ^)
2698
2699 (python-skeleton-define def nil
2700 "Function name: "
2701 "def " str "(" ("Parameter, %s: "
2702 (unless (equal ?\( (char-before)) ", ")
2703 str) "):" \n
2704 "\"\"\"" - "\"\"\"" \n
2705 > _ \n)
2706
2707 (python-skeleton-define class nil
2708 "Class name: "
2709 "class " str "(" ("Inheritance, %s: "
2710 (unless (equal ?\( (char-before)) ", ")
2711 str)
2712 & ")" | -2
2713 ":" \n
2714 "\"\"\"" - "\"\"\"" \n
2715 > _ \n)
2716
2717 (defun python-skeleton-add-menu-items ()
2718 "Add menu items to Python->Skeletons menu."
2719 (let ((skeletons (sort python-skeleton-available 'string<))
2720 (items))
2721 (dolist (skeleton skeletons)
2722 (easy-menu-add-item
2723 nil '("Python" "Skeletons")
2724 `[,(format
2725 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
2726 ,skeleton t]))))
2727 \f
2728 ;;; FFAP
2729
2730 (defcustom python-ffap-setup-code
2731 "def __FFAP_get_module_path(module):
2732 try:
2733 import os
2734 path = __import__(module).__file__
2735 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2736 path = path[:-1]
2737 return path
2738 except:
2739 return ''"
2740 "Python code to get a module path."
2741 :type 'string
2742 :group 'python)
2743
2744 (defcustom python-ffap-string-code
2745 "__FFAP_get_module_path('''%s''')\n"
2746 "Python code used to get a string with the path of a module."
2747 :type 'string
2748 :group 'python)
2749
2750 (defun python-ffap-module-path (module)
2751 "Function for `ffap-alist' to return path for MODULE."
2752 (let ((process (or
2753 (and (eq major-mode 'inferior-python-mode)
2754 (get-buffer-process (current-buffer)))
2755 (python-shell-get-process))))
2756 (if (not process)
2757 nil
2758 (let ((module-file
2759 (python-shell-send-string-no-output
2760 (format python-ffap-string-code module) process)))
2761 (when module-file
2762 (substring-no-properties module-file 1 -1))))))
2763
2764 (eval-after-load "ffap"
2765 '(progn
2766 (push '(python-mode . python-ffap-module-path) ffap-alist)
2767 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2768
2769 \f
2770 ;;; Code check
2771
2772 (defcustom python-check-command
2773 "pyflakes"
2774 "Command used to check a Python file."
2775 :type 'string
2776 :group 'python)
2777
2778 (defcustom python-check-buffer-name
2779 "*Python check: %s*"
2780 "Buffer name used for check commands."
2781 :type 'string
2782 :group 'python)
2783
2784 (defvar python-check-custom-command nil
2785 "Internal use.")
2786
2787 (defun python-check (command)
2788 "Check a Python file (default current buffer's file).
2789 Runs COMMAND, a shell command, as if by `compile'. See
2790 `python-check-command' for the default."
2791 (interactive
2792 (list (read-string "Check command: "
2793 (or python-check-custom-command
2794 (concat python-check-command " "
2795 (shell-quote-argument
2796 (or
2797 (let ((name (buffer-file-name)))
2798 (and name
2799 (file-name-nondirectory name)))
2800 "")))))))
2801 (setq python-check-custom-command command)
2802 (save-some-buffers (not compilation-ask-about-save) nil)
2803 (let ((process-environment (python-shell-calculate-process-environment))
2804 (exec-path (python-shell-calculate-exec-path)))
2805 (compilation-start command nil
2806 (lambda (mode-name)
2807 (format python-check-buffer-name command)))))
2808
2809 \f
2810 ;;; Eldoc
2811
2812 (defcustom python-eldoc-setup-code
2813 "def __PYDOC_get_help(obj):
2814 try:
2815 import inspect
2816 if hasattr(obj, 'startswith'):
2817 obj = eval(obj, globals())
2818 doc = inspect.getdoc(obj)
2819 if not doc and callable(obj):
2820 target = None
2821 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2822 target = obj.__init__
2823 objtype = 'class'
2824 else:
2825 target = obj
2826 objtype = 'def'
2827 if target:
2828 args = inspect.formatargspec(
2829 *inspect.getargspec(target)
2830 )
2831 name = obj.__name__
2832 doc = '{objtype} {name}{args}'.format(
2833 objtype=objtype, name=name, args=args
2834 )
2835 else:
2836 doc = doc.splitlines()[0]
2837 except:
2838 doc = ''
2839 try:
2840 exec('print doc')
2841 except SyntaxError:
2842 print(doc)"
2843 "Python code to setup documentation retrieval."
2844 :type 'string
2845 :group 'python)
2846
2847 (defcustom python-eldoc-string-code
2848 "__PYDOC_get_help('''%s''')\n"
2849 "Python code used to get a string with the documentation of an object."
2850 :type 'string
2851 :group 'python)
2852
2853 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
2854 "Internal implementation to get documentation at point.
2855 If not FORCE-INPUT is passed then what
2856 `python-info-current-symbol' returns will be used. If not
2857 FORCE-PROCESS is passed what `python-shell-get-process' returns
2858 is used."
2859 (let ((process (or force-process (python-shell-get-process))))
2860 (if (not process)
2861 (error "Eldoc needs an inferior Python process running")
2862 (let ((input (or force-input
2863 (python-info-current-symbol t))))
2864 (and input
2865 (python-shell-send-string-no-output
2866 (format python-eldoc-string-code input)
2867 process))))))
2868
2869 (defun python-eldoc-function ()
2870 "`eldoc-documentation-function' for Python.
2871 For this to work the best as possible you should call
2872 `python-shell-send-buffer' from time to time so context in
2873 inferior python process is updated properly."
2874 (python-eldoc--get-doc-at-point))
2875
2876 (defun python-eldoc-at-point (symbol)
2877 "Get help on SYMBOL using `help'.
2878 Interactively, prompt for symbol."
2879 (interactive
2880 (let ((symbol (python-info-current-symbol t))
2881 (enable-recursive-minibuffers t))
2882 (list (read-string (if symbol
2883 (format "Describe symbol (default %s): " symbol)
2884 "Describe symbol: ")
2885 nil nil symbol))))
2886 (message (python-eldoc--get-doc-at-point symbol)))
2887
2888 (add-to-list 'debug-ignored-errors
2889 "^Eldoc needs an inferior Python process running.")
2890
2891 \f
2892 ;;; Imenu
2893
2894 (defun python-imenu-prev-index-position ()
2895 "Python mode's `imenu-prev-index-position-function'."
2896 (let ((found))
2897 (while (and (setq found
2898 (re-search-backward python-nav-beginning-of-defun-regexp nil t))
2899 (not (python-info-looking-at-beginning-of-defun))))
2900 (and found
2901 (python-info-looking-at-beginning-of-defun)
2902 (python-info-current-defun))))
2903
2904 \f
2905 ;;; Misc helpers
2906
2907 (defun python-info-current-defun (&optional include-type)
2908 "Return name of surrounding function with Python compatible dotty syntax.
2909 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2910 This function is compatible to be used as
2911 `add-log-current-defun-function' since it returns nil if point is
2912 not inside a defun."
2913 (save-restriction
2914 (widen)
2915 (save-excursion
2916 (end-of-line 1)
2917 (let ((names)
2918 (starting-indentation
2919 (save-excursion
2920 (and
2921 (python-nav-beginning-of-defun 1)
2922 ;; This extra number is just for checking code
2923 ;; against indentation to work well on first run.
2924 (+ (current-indentation) 4))))
2925 (starting-point (point)))
2926 ;; Check point is inside a defun.
2927 (when (and starting-indentation
2928 (< starting-point
2929 (save-excursion
2930 (python-nav-end-of-defun)
2931 (point))))
2932 (catch 'exit
2933 (while (python-nav-beginning-of-defun 1)
2934 (when (< (current-indentation) starting-indentation)
2935 (setq starting-indentation (current-indentation))
2936 (setq names
2937 (cons
2938 (if (not include-type)
2939 (match-string-no-properties 1)
2940 (mapconcat 'identity
2941 (split-string
2942 (match-string-no-properties 0)) " "))
2943 names)))
2944 (and (= (current-indentation) 0) (throw 'exit t)))))
2945 (and names
2946 (mapconcat (lambda (string) string) names "."))))))
2947
2948 (defun python-info-current-symbol (&optional replace-self)
2949 "Return current symbol using dotty syntax.
2950 With optional argument REPLACE-SELF convert \"self\" to current
2951 parent defun name."
2952 (let ((name
2953 (and (not (python-syntax-comment-or-string-p))
2954 (with-syntax-table python-dotty-syntax-table
2955 (let ((sym (symbol-at-point)))
2956 (and sym
2957 (substring-no-properties (symbol-name sym))))))))
2958 (when name
2959 (if (not replace-self)
2960 name
2961 (let ((current-defun (python-info-current-defun)))
2962 (if (not current-defun)
2963 name
2964 (replace-regexp-in-string
2965 (python-rx line-start word-start "self" word-end ?.)
2966 (concat
2967 (mapconcat 'identity
2968 (butlast (split-string current-defun "\\."))
2969 ".") ".")
2970 name)))))))
2971
2972 (defun python-info-statement-starts-block-p ()
2973 "Return non-nil if current statement opens a block."
2974 (save-excursion
2975 (python-nav-beginning-of-statement)
2976 (looking-at (python-rx block-start))))
2977
2978 (defun python-info-statement-ends-block-p ()
2979 "Return non-nil if point is at end of block."
2980 (let ((end-of-block-pos (save-excursion
2981 (python-nav-end-of-block)))
2982 (end-of-statement-pos (save-excursion
2983 (python-nav-end-of-statement))))
2984 (and end-of-block-pos end-of-statement-pos
2985 (= end-of-block-pos end-of-statement-pos))))
2986
2987 (defun python-info-beginning-of-statement-p ()
2988 "Return non-nil if point is at beginning of statement."
2989 (= (point) (save-excursion
2990 (python-nav-beginning-of-statement)
2991 (point))))
2992
2993 (defun python-info-end-of-statement-p ()
2994 "Return non-nil if point is at end of statement."
2995 (= (point) (save-excursion
2996 (python-nav-end-of-statement)
2997 (point))))
2998
2999 (defun python-info-beginning-of-block-p ()
3000 "Return non-nil if point is at beginning of block."
3001 (and (python-info-beginning-of-statement-p)
3002 (python-info-statement-starts-block-p)))
3003
3004 (defun python-info-end-of-block-p ()
3005 "Return non-nil if point is at end of block."
3006 (and (python-info-end-of-statement-p)
3007 (python-info-statement-ends-block-p)))
3008
3009 (defun python-info-closing-block ()
3010 "Return the point of the block the current line closes."
3011 (let ((closing-word (save-excursion
3012 (back-to-indentation)
3013 (current-word)))
3014 (indentation (current-indentation)))
3015 (when (member closing-word python-indent-dedenters)
3016 (save-excursion
3017 (forward-line -1)
3018 (while (and (> (current-indentation) indentation)
3019 (not (bobp))
3020 (not (back-to-indentation))
3021 (forward-line -1)))
3022 (back-to-indentation)
3023 (cond
3024 ((not (equal indentation (current-indentation))) nil)
3025 ((string= closing-word "elif")
3026 (when (member (current-word) '("if" "elif"))
3027 (point-marker)))
3028 ((string= closing-word "else")
3029 (when (member (current-word) '("if" "elif" "except" "for" "while"))
3030 (point-marker)))
3031 ((string= closing-word "except")
3032 (when (member (current-word) '("try"))
3033 (point-marker)))
3034 ((string= closing-word "finally")
3035 (when (member (current-word) '("except" "else"))
3036 (point-marker))))))))
3037
3038 (defun python-info-closing-block-message (&optional closing-block-point)
3039 "Message the contents of the block the current line closes.
3040 With optional argument CLOSING-BLOCK-POINT use that instead of
3041 recalculating it calling `python-info-closing-block'."
3042 (let ((point (or closing-block-point (python-info-closing-block))))
3043 (when point
3044 (save-restriction
3045 (widen)
3046 (message "Closes %s" (save-excursion
3047 (goto-char point)
3048 (back-to-indentation)
3049 (buffer-substring
3050 (point) (line-end-position))))))))
3051
3052 (defun python-info-line-ends-backslash-p (&optional line-number)
3053 "Return non-nil if current line ends with backslash.
3054 With optional argument LINE-NUMBER, check that line instead."
3055 (save-excursion
3056 (save-restriction
3057 (widen)
3058 (when line-number
3059 (goto-char line-number))
3060 (while (and (not (eobp))
3061 (goto-char (line-end-position))
3062 (python-syntax-context 'paren)
3063 (not (equal (char-before (point)) ?\\)))
3064 (forward-line 1))
3065 (when (equal (char-before) ?\\)
3066 (point-marker)))))
3067
3068 (defun python-info-beginning-of-backslash (&optional line-number)
3069 "Return the point where the backslashed line start.
3070 Optional argument LINE-NUMBER forces the line number to check against."
3071 (save-excursion
3072 (save-restriction
3073 (widen)
3074 (when line-number
3075 (goto-char line-number))
3076 (when (python-info-line-ends-backslash-p)
3077 (while (save-excursion
3078 (goto-char (line-beginning-position))
3079 (python-syntax-context 'paren))
3080 (forward-line -1))
3081 (back-to-indentation)
3082 (point-marker)))))
3083
3084 (defun python-info-continuation-line-p ()
3085 "Check if current line is continuation of another.
3086 When current line is continuation of another return the point
3087 where the continued line ends."
3088 (save-excursion
3089 (save-restriction
3090 (widen)
3091 (let* ((context-type (progn
3092 (back-to-indentation)
3093 (python-syntax-context-type)))
3094 (line-start (line-number-at-pos))
3095 (context-start (when context-type
3096 (python-syntax-context context-type))))
3097 (cond ((equal context-type 'paren)
3098 ;; Lines inside a paren are always a continuation line
3099 ;; (except the first one).
3100 (python-util-forward-comment -1)
3101 (point-marker))
3102 ((member context-type '(string comment))
3103 ;; move forward an roll again
3104 (goto-char context-start)
3105 (python-util-forward-comment)
3106 (python-info-continuation-line-p))
3107 (t
3108 ;; Not within a paren, string or comment, the only way
3109 ;; we are dealing with a continuation line is that
3110 ;; previous line contains a backslash, and this can
3111 ;; only be the previous line from current
3112 (back-to-indentation)
3113 (python-util-forward-comment -1)
3114 (when (and (equal (1- line-start) (line-number-at-pos))
3115 (python-info-line-ends-backslash-p))
3116 (point-marker))))))))
3117
3118 (defun python-info-block-continuation-line-p ()
3119 "Return non-nil if current line is a continuation of a block."
3120 (save-excursion
3121 (when (python-info-continuation-line-p)
3122 (forward-line -1)
3123 (back-to-indentation)
3124 (when (looking-at (python-rx block-start))
3125 (point-marker)))))
3126
3127 (defun python-info-assignment-continuation-line-p ()
3128 "Check if current line is a continuation of an assignment.
3129 When current line is continuation of another with an assignment
3130 return the point of the first non-blank character after the
3131 operator."
3132 (save-excursion
3133 (when (python-info-continuation-line-p)
3134 (forward-line -1)
3135 (back-to-indentation)
3136 (when (and (not (looking-at (python-rx block-start)))
3137 (and (re-search-forward (python-rx not-simple-operator
3138 assignment-operator
3139 not-simple-operator)
3140 (line-end-position) t)
3141 (not (python-syntax-context-type))))
3142 (skip-syntax-forward "\s")
3143 (point-marker)))))
3144
3145 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
3146 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3147 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
3148 (save-excursion
3149 (beginning-of-line 1)
3150 (looking-at python-nav-beginning-of-defun-regexp))))
3151
3152 (defun python-info-current-line-comment-p ()
3153 "Check if current line is a comment line."
3154 (char-equal (or (char-after (+ (point) (current-indentation))) ?_) ?#))
3155
3156 (defun python-info-current-line-empty-p ()
3157 "Check if current line is empty, ignoring whitespace."
3158 (save-excursion
3159 (beginning-of-line 1)
3160 (looking-at
3161 (python-rx line-start (* whitespace)
3162 (group (* not-newline))
3163 (* whitespace) line-end))
3164 (string-equal "" (match-string-no-properties 1))))
3165
3166 \f
3167 ;;; Utility functions
3168
3169 (defun python-util-position (item seq)
3170 "Find the first occurrence of ITEM in SEQ.
3171 Return the index of the matching item, or nil if not found."
3172 (let ((member-result (member item seq)))
3173 (when member-result
3174 (- (length seq) (length member-result)))))
3175
3176 ;; Stolen from org-mode
3177 (defun python-util-clone-local-variables (from-buffer &optional regexp)
3178 "Clone local variables from FROM-BUFFER.
3179 Optional argument REGEXP selects variables to clone and defaults
3180 to \"^python-\"."
3181 (mapc
3182 (lambda (pair)
3183 (and (symbolp (car pair))
3184 (string-match (or regexp "^python-")
3185 (symbol-name (car pair)))
3186 (set (make-local-variable (car pair))
3187 (cdr pair))))
3188 (buffer-local-variables from-buffer)))
3189
3190 (defun python-util-forward-comment (&optional direction)
3191 "Python mode specific version of `forward-comment'.
3192 Optional argument DIRECTION defines the direction to move to."
3193 (let ((comment-start (python-syntax-context 'comment))
3194 (factor (if (< (or direction 0) 0)
3195 -99999
3196 99999)))
3197 (when comment-start
3198 (goto-char comment-start))
3199 (forward-comment factor)))
3200
3201 \f
3202 ;;;###autoload
3203 (define-derived-mode python-mode prog-mode "Python"
3204 "Major mode for editing Python files.
3205
3206 \\{python-mode-map}
3207 Entry to this mode calls the value of `python-mode-hook'
3208 if that value is non-nil."
3209 (set (make-local-variable 'tab-width) 8)
3210 (set (make-local-variable 'indent-tabs-mode) nil)
3211
3212 (set (make-local-variable 'comment-start) "# ")
3213 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
3214
3215 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3216 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3217
3218 (set (make-local-variable 'forward-sexp-function)
3219 'python-nav-forward-sexp)
3220
3221 (set (make-local-variable 'font-lock-defaults)
3222 '(python-font-lock-keywords nil nil nil nil))
3223
3224 (set (make-local-variable 'syntax-propertize-function)
3225 python-syntax-propertize-function)
3226
3227 (set (make-local-variable 'indent-line-function)
3228 #'python-indent-line-function)
3229 (set (make-local-variable 'indent-region-function) #'python-indent-region)
3230
3231 (set (make-local-variable 'paragraph-start) "\\s-*$")
3232 (set (make-local-variable 'fill-paragraph-function)
3233 'python-fill-paragraph)
3234
3235 (set (make-local-variable 'beginning-of-defun-function)
3236 #'python-nav-beginning-of-defun)
3237 (set (make-local-variable 'end-of-defun-function)
3238 #'python-nav-end-of-defun)
3239
3240 (add-hook 'completion-at-point-functions
3241 'python-completion-complete-at-point nil 'local)
3242
3243 (add-hook 'post-self-insert-hook
3244 'python-indent-post-self-insert-function nil 'local)
3245
3246 (set (make-local-variable 'imenu-extract-index-name-function)
3247 #'python-info-current-defun)
3248
3249 (set (make-local-variable 'imenu-prev-index-position-function)
3250 #'python-imenu-prev-index-position)
3251
3252 (set (make-local-variable 'add-log-current-defun-function)
3253 #'python-info-current-defun)
3254
3255 (add-hook 'which-func-functions #'python-info-current-defun nil t)
3256
3257 (set (make-local-variable 'skeleton-further-elements)
3258 '((abbrev-mode nil)
3259 (< '(backward-delete-char-untabify (min python-indent-offset
3260 (current-column))))
3261 (^ '(- (1+ (current-indentation))))))
3262
3263 (set (make-local-variable 'eldoc-documentation-function)
3264 #'python-eldoc-function)
3265
3266 (add-to-list 'hs-special-modes-alist
3267 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
3268 ,(lambda (arg)
3269 (python-nav-end-of-defun)) nil))
3270
3271 (set (make-local-variable 'mode-require-final-newline) t)
3272
3273 (set (make-local-variable 'outline-regexp)
3274 (python-rx (* space) block-start))
3275 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
3276 (set (make-local-variable 'outline-level)
3277 #'(lambda ()
3278 "`outline-level' function for Python mode."
3279 (1+ (/ (current-indentation) python-indent-offset))))
3280
3281 (python-skeleton-add-menu-items)
3282
3283 (make-local-variable 'python-shell-internal-buffer)
3284
3285 (when python-indent-guess-indent-offset
3286 (python-indent-guess-indent-offset)))
3287
3288
3289 (provide 'python)
3290
3291 ;; Local Variables:
3292 ;; coding: utf-8
3293 ;; indent-tabs-mode: nil
3294 ;; End:
3295
3296 ;;; python.el ends here