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