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