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