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