]> code.delx.au - gnu-emacs/blob - lisp/progmodes/python.el
Implemented simple virtualenv setup via python-shell-virtualenv-path variable.
[gnu-emacs] / lisp / progmodes / python.el
1 ;;; python.el --- Python's flying circus support for Emacs
2
3 ;; Copyright (C) 2010, 2011 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.23.1
8 ;; Maintainer: FSF
9 ;; Created: Jul 2010
10 ;; Keywords: languages
11
12 ;; This file is NOT part of GNU Emacs.
13
14 ;; python.el is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; python.el is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with python.el. 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 ;; While it probably has less features than Dave Love's python.el and
34 ;; PSF's python-mode.el it provides the main stuff you'll need while
35 ;; keeping it simple :)
36
37 ;; Implements Syntax highlighting, Indentation, Movement, Shell
38 ;; interaction, Shell completion, Shell virtualenv support, Pdb
39 ;; tracking, Symbol completion, Skeletons, FFAP, Code Check, Eldoc,
40 ;; imenu.
41
42 ;; Syntax highlighting: Fontification of code is provided and supports
43 ;; python's triple quoted strings properly.
44
45 ;; Indentation: Automatic indentation with indentation cycling is
46 ;; provided, it allows you to navigate different available levels of
47 ;; indentation by hitting <tab> several times. Also when inserting a
48 ;; colon the `python-indent-electric-colon' command is invoked and
49 ;; causes the current line to be dedented automatically if needed.
50
51 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
52 ;; properly implemented. Also there are specialized
53 ;; `forward-sentence' and `backward-sentence' replacements
54 ;; (`python-nav-forward-sentence', `python-nav-backward-sentence'
55 ;; respectively). Extra functions `python-nav-sentence-start' and
56 ;; `python-nav-sentence-end' are included to move to the beginning and
57 ;; to the end of a setence while taking care of multiline definitions.
58
59 ;; Shell interaction: is provided and allows you easily execute any
60 ;; block of code of your current buffer in an inferior Python process.
61
62 ;; Shell completion: hitting tab will try to complete the current
63 ;; word. Shell completion is implemented in a manner that if you
64 ;; change the `python-shell-interpreter' to any other (for example
65 ;; IPython) it should be easy to integrate another way to calculate
66 ;; completions. You just need to specify your custom
67 ;; `python-shell-completion-setup-code' and
68 ;; `python-shell-completion-string-code'.
69
70 ;; Here is a complete example of the settings you would use for
71 ;; iPython
72
73 ;; (setq
74 ;; python-shell-interpreter "ipython"
75 ;; python-shell-interpreter-args ""
76 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
77 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
78 ;; python-shell-completion-setup-code ""
79 ;; python-shell-completion-string-code
80 ;; "';'.join(__IP.complete('''%s'''))\n")
81
82 ;; Please note that the default completion system depends on the
83 ;; readline module, so if you are using some Operating System that
84 ;; bundles Python without it (like Windows) just install the
85 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
86 ;; you should be good to go.
87
88 ;; Shell virtualenv support: The shell also contains support for
89 ;; virtualenvs and other special environment modifications thanks to
90 ;; `python-shell-process-environment' and `python-shell-exec-path'.
91 ;; These two variables allows you to modify execution paths and
92 ;; enviroment variables to make easy for you to setup virtualenv rules
93 ;; or behavior modifications when running shells. Here is an example
94 ;; of how to make shell processes to be run using the /path/to/env/
95 ;; virtualenv:
96
97 ;; (setq python-shell-process-environment
98 ;; (list
99 ;; (format "PATH=%s" (mapconcat
100 ;; 'identity
101 ;; (reverse
102 ;; (cons (getenv "PATH")
103 ;; '("/path/to/env/bin/")))
104 ;; ":"))
105 ;; "VIRTUAL_ENV=/path/to/env/"))
106 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
107
108 ;; Since the above is cumbersome and can be programatically
109 ;; calculated, the variable `python-shell-virtualenv-path' is
110 ;; provided. When this variable is set with the path of the
111 ;; virtualenv to use, `process-environment' and `exec-path' get proper
112 ;; values in order to run shells inside the specified virtualenv. So
113 ;; the following will achieve the same as the previous example:
114
115 ;; (setq python-shell-virtualenv-path "/path/to/env/")
116
117 ;; Pdb tracking: when you execute a block of code that contains some
118 ;; call to pdb (or ipdb) it will prompt the block of code and will
119 ;; follow the execution of pdb marking the current line with an arrow.
120
121 ;; Symbol completion: you can complete the symbol at point. It uses
122 ;; the shell completion in background so you should run
123 ;; `python-shell-send-buffer' from time to time to get better results.
124
125 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
126 ;; def, for, if, try and while. These skeletons are integrated with
127 ;; dabbrev. If you have `dabbrev-mode' activated and
128 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
129 ;; the name of any of those defined and hit SPC, they will be
130 ;; automatically expanded.
131
132 ;; FFAP: You can find the filename for a given module when using ffap
133 ;; out of the box. This feature needs an inferior python shell
134 ;; running.
135
136 ;; Code check: Check the current file for errors with `python-check'
137 ;; using the program defined in `python-check-command'.
138
139 ;; Eldoc: returns documentation for object at point by using the
140 ;; inferior python subprocess to inspect its documentation. As you
141 ;; might guessed you should run `python-shell-send-buffer' from time
142 ;; to time to get better results too.
143
144 ;; imenu: This mode supports imenu. It builds a plain or tree menu
145 ;; depending on the value of `python-imenu-make-tree'. Also you can
146 ;; customize if menu items should include its type using
147 ;; `python-imenu-include-defun-type'.
148
149 ;; If you used python-mode.el you probably will miss auto-indentation
150 ;; when inserting newlines. To achieve the same behavior you have
151 ;; two options:
152
153 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
154
155 ;; 2) Add the following hook in your .emacs:
156
157 ;; (add-hook 'python-mode-hook
158 ;; #'(lambda ()
159 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
160
161 ;; I'd recommend the first one since you'll get the same behavior for
162 ;; all modes out-of-the-box.
163
164 ;;; Installation:
165
166 ;; Add this to your .emacs:
167
168 ;; (add-to-list 'load-path "/folder/containing/file")
169 ;; (require 'python)
170
171 ;;; TODO:
172
173 ;;; Code:
174
175 (require 'ansi-color)
176 (require 'comint)
177
178 (eval-when-compile
179 (require 'cl)
180 ;; Avoid compiler warnings
181 (defvar view-return-to-alist)
182 (defvar compilation-error-regexp-alist)
183 (defvar outline-heading-end-regexp))
184
185 (autoload 'comint-mode "comint")
186
187 ;;;###autoload
188 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
189 ;;;###autoload
190 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
191
192 (defgroup python nil
193 "Python Language's flying circus support for Emacs."
194 :group 'languages
195 :version "23.2"
196 :link '(emacs-commentary-link "python"))
197
198 \f
199 ;;; Bindings
200
201 (defvar python-mode-map
202 (let ((map (make-sparse-keymap)))
203 ;; Movement
204 (substitute-key-definition 'backward-sentence
205 'python-nav-backward-sentence
206 map global-map)
207 (substitute-key-definition 'forward-sentence
208 'python-nav-forward-sentence
209 map global-map)
210 ;; Indent specific
211 (define-key map "\177" 'python-indent-dedent-line-backspace)
212 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
213 (define-key map "\C-c<" 'python-indent-shift-left)
214 (define-key map "\C-c>" 'python-indent-shift-right)
215 (define-key map ":" 'python-indent-electric-colon)
216 ;; Skeletons
217 (define-key map "\C-c\C-tc" 'python-skeleton-class)
218 (define-key map "\C-c\C-td" 'python-skeleton-def)
219 (define-key map "\C-c\C-tf" 'python-skeleton-for)
220 (define-key map "\C-c\C-ti" 'python-skeleton-if)
221 (define-key map "\C-c\C-tt" 'python-skeleton-try)
222 (define-key map "\C-c\C-tw" 'python-skeleton-while)
223 ;; Shell interaction
224 (define-key map "\C-c\C-s" 'python-shell-send-string)
225 (define-key map "\C-c\C-r" 'python-shell-send-region)
226 (define-key map "\C-\M-x" 'python-shell-send-defun)
227 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
228 (define-key map "\C-c\C-l" 'python-shell-send-file)
229 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
230 ;; Some util commands
231 (define-key map "\C-c\C-v" 'python-check)
232 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
233 ;; Utilities
234 (substitute-key-definition 'complete-symbol 'completion-at-point
235 map global-map)
236 (easy-menu-define python-menu map "Python Mode menu"
237 `("Python"
238 :help "Python-specific Features"
239 ["Shift region left" python-indent-shift-left :active mark-active
240 :help "Shift region left by a single indentation step"]
241 ["Shift region right" python-indent-shift-right :active mark-active
242 :help "Shift region right by a single indentation step"]
243 "-"
244 ["Mark def/class" mark-defun
245 :help "Mark outermost definition around point"]
246 "-"
247 ["Start of def/class" beginning-of-defun
248 :help "Go to start of outermost definition around point"]
249 ["End of def/class" end-of-defun
250 :help "Go to end of definition around point"]
251 "-"
252 ("Skeletons")
253 "-"
254 ["Start interpreter" run-python
255 :help "Run inferior Python process in a separate buffer"]
256 ["Switch to shell" python-shell-switch-to-shell
257 :help "Switch to running inferior Python process"]
258 ["Eval string" python-shell-send-string
259 :help "Eval string in inferior Python session"]
260 ["Eval buffer" python-shell-send-buffer
261 :help "Eval buffer in inferior Python session"]
262 ["Eval region" python-shell-send-region
263 :help "Eval region in inferior Python session"]
264 ["Eval defun" python-shell-send-defun
265 :help "Eval defun in inferior Python session"]
266 ["Eval file" python-shell-send-file
267 :help "Eval file in inferior Python session"]
268 ["Debugger" pdb :help "Run pdb under GUD"]
269 "-"
270 ["Check file" python-check
271 :help "Check file for errors"]
272 ["Help on symbol" python-eldoc-at-point
273 :help "Get help on symbol at point"]
274 ["Complete symbol" completion-at-point
275 :help "Complete symbol before point"]))
276 map)
277 "Keymap for `python-mode'.")
278
279 \f
280 ;;; Python specialized rx
281
282 (eval-when-compile
283 (defconst python-rx-constituents
284 (list
285 `(block-start . ,(rx symbol-start
286 (or "def" "class" "if" "elif" "else" "try"
287 "except" "finally" "for" "while" "with")
288 symbol-end))
289 `(decorator . ,(rx line-start (* space) ?@ (any letter ?_)
290 (* (any word ?_))))
291 `(defun . ,(rx symbol-start (or "def" "class") symbol-end))
292 `(symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
293 `(open-paren . ,(rx (or "{" "[" "(")))
294 `(close-paren . ,(rx (or "}" "]" ")")))
295 `(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
296 `(not-simple-operator . ,(rx (not (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
297 `(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
298 "=" "%" "**" "//" "<<" ">>" "<=" "!="
299 "==" ">=" "is" "not")))
300 `(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
301 ">>=" "<<=" "&=" "^=" "|="))))
302 "Additional Python specific sexps for `python-rx'"))
303
304 (defmacro python-rx (&rest regexps)
305 "Python mode specialized rx macro which supports common python named REGEXPS."
306 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
307 (cond ((null regexps)
308 (error "No regexp"))
309 ((cdr regexps)
310 (rx-to-string `(and ,@regexps) t))
311 (t
312 (rx-to-string (car regexps) t)))))
313
314 \f
315 ;;; Font-lock and syntax
316
317 (defvar python-font-lock-keywords
318 ;; Keywords
319 `(,(rx symbol-start
320 (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
321 "assert" "else" "if" "pass" "yield" "break" "except" "import"
322 "print" "class" "exec" "in" "raise" "continue" "finally" "is"
323 "return" "def" "for" "lambda" "try" "self")
324 symbol-end)
325 ;; functions
326 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
327 (1 font-lock-function-name-face))
328 ;; classes
329 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
330 (1 font-lock-type-face))
331 ;; Constants
332 (,(rx symbol-start
333 ;; copyright, license, credits, quit, exit are added by the
334 ;; site module and since they are not intended to be used in
335 ;; programs they are not added here either.
336 (or "None" "True" "False" "Ellipsis" "__debug__" "NotImplemented")
337 symbol-end) . font-lock-constant-face)
338 ;; Decorators.
339 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
340 (0+ "." (1+ (or word ?_)))))
341 (1 font-lock-type-face))
342 ;; Builtin Exceptions
343 (,(rx symbol-start
344 (or "ArithmeticError" "AssertionError" "AttributeError"
345 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
346 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
347 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
348 "ImportWarning" "IndentationError" "IndexError" "KeyError"
349 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
350 "NotImplementedError" "OSError" "OverflowError"
351 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
352 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
353 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
354 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
355 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
356 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
357 symbol-end) . font-lock-type-face)
358 ;; Builtins
359 (,(rx symbol-start
360 (or "_" "__doc__" "__import__" "__name__" "__package__" "abs" "all"
361 "any" "apply" "basestring" "bin" "bool" "buffer" "bytearray"
362 "bytes" "callable" "chr" "classmethod" "cmp" "coerce" "compile"
363 "complex" "delattr" "dict" "dir" "divmod" "enumerate" "eval"
364 "execfile" "file" "filter" "float" "format" "frozenset"
365 "getattr" "globals" "hasattr" "hash" "help" "hex" "id" "input"
366 "int" "intern" "isinstance" "issubclass" "iter" "len" "list"
367 "locals" "long" "map" "max" "min" "next" "object" "oct" "open"
368 "ord" "pow" "print" "property" "range" "raw_input" "reduce"
369 "reload" "repr" "reversed" "round" "set" "setattr" "slice"
370 "sorted" "staticmethod" "str" "sum" "super" "tuple" "type"
371 "unichr" "unicode" "vars" "xrange" "zip")
372 symbol-end) . font-lock-builtin-face)
373 ;; asignations
374 ;; support for a = b = c = 5
375 (,(lambda (limit)
376 (let ((re (python-rx (group (+ (any word ?. ?_)))
377 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
378 assignment-operator)))
379 (when (re-search-forward re limit t)
380 (while (and (python-info-ppss-context 'paren)
381 (re-search-forward re limit t)))
382 (if (and (not (python-info-ppss-context 'paren))
383 (not (equal (char-after (point-marker)) ?=)))
384 t
385 (set-match-data nil)))))
386 (1 font-lock-variable-name-face nil nil))
387 ;; support for a, b, c = (1, 2, 3)
388 (,(lambda (limit)
389 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
390 (* ?, (* space) (+ (any word ?. ?_)) (* space))
391 ?, (* space) (+ (any word ?. ?_)) (* space)
392 assignment-operator)))
393 (when (and (re-search-forward re limit t)
394 (goto-char (nth 3 (match-data))))
395 (while (and (python-info-ppss-context 'paren)
396 (re-search-forward re limit t))
397 (goto-char (nth 3 (match-data))))
398 (if (not (python-info-ppss-context 'paren))
399 t
400 (set-match-data nil)))))
401 (1 font-lock-variable-name-face nil nil))))
402
403 (defconst python-font-lock-syntactic-keywords
404 ;; Make outer chars of matching triple-quote sequences into generic
405 ;; string delimiters. Fixme: Is there a better way?
406 ;; First avoid a sequence preceded by an odd number of backslashes.
407 `((,(concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix.
408 "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
409 (3 (python-quote-syntax)))))
410
411 (defun python-quote-syntax ()
412 "Put `syntax-table' property correctly on triple quote.
413 Used for syntactic keywords. N is the match number (1, 2 or 3)."
414 ;; Given a triple quote, we have to check the context to know
415 ;; whether this is an opening or closing triple or whether it's
416 ;; quoted anyhow, and should be ignored. (For that we need to do
417 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
418 ;; to use it here despite initial worries.) We also have to sort
419 ;; out a possible prefix -- well, we don't _have_ to, but I think it
420 ;; should be treated as part of the string.
421
422 ;; Test cases:
423 ;; ur"""ar""" x='"' # """
424 ;; x = ''' """ ' a
425 ;; '''
426 ;; x '"""' x """ \"""" x
427 (save-excursion
428 (goto-char (match-beginning 0))
429 (let ((syntax (save-match-data (syntax-ppss))))
430 (cond
431 ((eq t (nth 3 syntax)) ; after unclosed fence
432 ;; Consider property for the last char if in a fenced string.
433 (goto-char (nth 8 syntax)) ; fence position
434 (skip-chars-forward "uUrR") ; skip any prefix
435 ;; Is it a matching sequence?
436 (if (eq (char-after) (char-after (match-beginning 2)))
437 (put-text-property (match-beginning 3) (match-end 3)
438 'syntax-table (string-to-syntax "|"))))
439 ((match-end 1)
440 ;; Consider property for initial char, accounting for prefixes.
441 (put-text-property (match-beginning 1) (match-end 1)
442 'syntax-table (string-to-syntax "|")))
443 (t
444 ;; Consider property for initial char, accounting for prefixes.
445 (put-text-property (match-beginning 2) (match-end 2)
446 'syntax-table (string-to-syntax "|"))))
447 )))
448
449 (defvar python-mode-syntax-table
450 (let ((table (make-syntax-table)))
451 ;; Give punctuation syntax to ASCII that normally has symbol
452 ;; syntax or has word syntax and isn't a letter.
453 (let ((symbol (string-to-syntax "_"))
454 (sst (standard-syntax-table)))
455 (dotimes (i 128)
456 (unless (= i ?_)
457 (if (equal symbol (aref sst i))
458 (modify-syntax-entry i "." table)))))
459 (modify-syntax-entry ?$ "." table)
460 (modify-syntax-entry ?% "." table)
461 ;; exceptions
462 (modify-syntax-entry ?# "<" table)
463 (modify-syntax-entry ?\n ">" table)
464 (modify-syntax-entry ?' "\"" table)
465 (modify-syntax-entry ?` "$" table)
466 table)
467 "Syntax table for Python files.")
468
469 (defvar python-dotty-syntax-table
470 (let ((table (make-syntax-table python-mode-syntax-table)))
471 (modify-syntax-entry ?. "w" table)
472 (modify-syntax-entry ?_ "w" table)
473 table)
474 "Dotty syntax table for Python files.
475 It makes underscores and dots word constituent chars.")
476
477 \f
478 ;;; Indentation
479
480 (defcustom python-indent-offset 4
481 "Default indentation offset for Python."
482 :group 'python
483 :type 'integer
484 :safe 'integerp)
485
486 (defcustom python-indent-guess-indent-offset t
487 "Non-nil tells Python mode to guess `python-indent-offset' value."
488 :type 'boolean
489 :group 'python)
490
491 (defvar python-indent-current-level 0
492 "Current indentation level `python-indent-line-function' is using.")
493
494 (defvar python-indent-levels '(0)
495 "Levels of indentation available for `python-indent-line-function'.")
496
497 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
498 "List of words that should be dedented.
499 These make `python-indent-calculate-indentation' subtract the value of
500 `python-indent-offset'.")
501
502 (defun python-indent-guess-indent-offset ()
503 "Guess and set `python-indent-offset' for the current buffer."
504 (save-excursion
505 (save-restriction
506 (widen)
507 (goto-char (point-min))
508 (let ((found-block))
509 (while (and (not found-block)
510 (re-search-forward
511 (python-rx line-start block-start) nil t))
512 (when (and (not (python-info-ppss-context 'string))
513 (not (python-info-ppss-context 'comment))
514 (progn
515 (goto-char (line-end-position))
516 (forward-comment -9999)
517 (eq ?: (char-before))))
518 (setq found-block t)))
519 (if (not found-block)
520 (message "Can't guess python-indent-offset, using defaults: %s"
521 python-indent-offset)
522 (while (and (progn
523 (goto-char (line-end-position))
524 (python-info-continuation-line-p))
525 (not (eobp)))
526 (forward-line 1))
527 (forward-line 1)
528 (forward-comment 9999)
529 (let ((indent-offset (current-indentation)))
530 (when (> indent-offset 0)
531 (setq python-indent-offset indent-offset))))))))
532
533 (defun python-indent-context ()
534 "Get information on indentation context.
535 Context information is returned with a cons with the form:
536 \(STATUS . START)
537
538 Where status can be any of the following symbols:
539 * inside-paren: If point in between (), {} or []
540 * inside-string: If point is inside a string
541 * after-backslash: Previous line ends in a backslash
542 * after-beginning-of-block: Point is after beginning of block
543 * after-line: Point is after normal line
544 * no-indent: Point is at beginning of buffer or other special case
545 START is the buffer position where the sexp starts."
546 (save-restriction
547 (widen)
548 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
549 (start))
550 (cons
551 (cond
552 ;; Beginning of buffer
553 ((save-excursion
554 (goto-char (line-beginning-position))
555 (bobp))
556 'no-indent)
557 ;; Inside a paren
558 ((setq start (python-info-ppss-context 'paren ppss))
559 'inside-paren)
560 ;; Inside string
561 ((setq start (python-info-ppss-context 'string ppss))
562 'inside-string)
563 ;; After backslash
564 ((setq start (when (not (or (python-info-ppss-context 'string ppss)
565 (python-info-ppss-context 'comment ppss)))
566 (let ((line-beg-pos (line-beginning-position)))
567 (when (eq ?\\ (char-before (1- line-beg-pos)))
568 (- line-beg-pos 2)))))
569 'after-backslash)
570 ;; After beginning of block
571 ((setq start (save-excursion
572 (let ((block-regexp (python-rx block-start))
573 (block-start-line-end ":[[:space:]]*$"))
574 (back-to-indentation)
575 (while (and (forward-comment -9999) (not (bobp))))
576 (back-to-indentation)
577 (when (or (python-info-continuation-line-p)
578 (and (not (looking-at block-regexp))
579 (save-excursion
580 (re-search-forward
581 block-start-line-end
582 (line-end-position) t))))
583 (while (and (forward-line -1)
584 (python-info-continuation-line-p)
585 (not (bobp))))
586 (when (not (looking-at block-regexp))
587 (forward-line 1)))
588 (back-to-indentation)
589 (when (and (looking-at block-regexp)
590 (or (re-search-forward
591 block-start-line-end
592 (line-end-position) t)
593 (python-info-continuation-line-p)))
594 (point-marker)))))
595 'after-beginning-of-block)
596 ;; After normal line
597 ((setq start (save-excursion
598 (while (and (forward-comment -9999) (not (bobp))))
599 (python-nav-sentence-start)
600 (point-marker)))
601 'after-line)
602 ;; Do not indent
603 (t 'no-indent))
604 start))))
605
606 (defun python-indent-calculate-indentation ()
607 "Calculate correct indentation offset for the current line."
608 (let* ((indentation-context (python-indent-context))
609 (context-status (car indentation-context))
610 (context-start (cdr indentation-context)))
611 (save-restriction
612 (widen)
613 (save-excursion
614 (case context-status
615 ('no-indent 0)
616 ('after-beginning-of-block
617 (goto-char context-start)
618 (+ (current-indentation) python-indent-offset))
619 ('after-line
620 (-
621 (save-excursion
622 (goto-char context-start)
623 (current-indentation))
624 (if (progn
625 (back-to-indentation)
626 (looking-at (regexp-opt python-indent-dedenters)))
627 python-indent-offset
628 0)))
629 ('inside-string
630 (goto-char context-start)
631 (current-indentation))
632 ('after-backslash
633 (let* ((block-continuation
634 (save-excursion
635 (forward-line -1)
636 (python-info-block-continuation-line-p)))
637 (assignment-continuation
638 (save-excursion
639 (forward-line -1)
640 (python-info-assignment-continuation-line-p)))
641 (dot-continuation
642 (save-excursion
643 (back-to-indentation)
644 (when (looking-at "\\.")
645 (forward-line -1)
646 (goto-char (line-end-position))
647 (while (and (re-search-backward "\\." (line-beginning-position) t)
648 (or (python-info-ppss-context 'comment)
649 (python-info-ppss-context 'string)
650 (python-info-ppss-context 'paren))))
651 (if (and (looking-at "\\.")
652 (not (or (python-info-ppss-context 'comment)
653 (python-info-ppss-context 'string)
654 (python-info-ppss-context 'paren))))
655 (current-column)
656 (+ (current-indentation) python-indent-offset)))))
657 (indentation (cond
658 (dot-continuation
659 dot-continuation)
660 (block-continuation
661 (goto-char block-continuation)
662 (re-search-forward
663 (python-rx block-start (* space))
664 (line-end-position) t)
665 (current-column))
666 (assignment-continuation
667 (goto-char assignment-continuation)
668 (re-search-forward
669 (python-rx simple-operator)
670 (line-end-position) t)
671 (forward-char 1)
672 (re-search-forward
673 (python-rx (* space))
674 (line-end-position) t)
675 (current-column))
676 (t
677 (goto-char context-start)
678 (if (not
679 (save-excursion
680 (back-to-indentation)
681 (looking-at
682 "\\(?:return\\|from\\|import\\)\s+")))
683 (current-indentation)
684 (+ (current-indentation)
685 (length
686 (match-string-no-properties 0))))))))
687 indentation))
688 ('inside-paren
689 (or (save-excursion
690 (skip-syntax-forward "\s" (line-end-position))
691 (when (and (looking-at (regexp-opt '(")" "]" "}")))
692 (not (forward-char 1))
693 (not (python-info-ppss-context 'paren)))
694 (goto-char context-start)
695 (back-to-indentation)
696 (current-column)))
697 (-
698 (save-excursion
699 (goto-char context-start)
700 (forward-char)
701 (save-restriction
702 (narrow-to-region
703 (line-beginning-position)
704 (line-end-position))
705 (forward-comment 9999))
706 (if (looking-at "$")
707 (+ (current-indentation) python-indent-offset)
708 (forward-comment 9999)
709 (current-column)))
710 (if (progn
711 (back-to-indentation)
712 (looking-at (regexp-opt '(")" "]" "}"))))
713 python-indent-offset
714 0)))))))))
715
716 (defun python-indent-calculate-levels ()
717 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
718 (let* ((indentation (python-indent-calculate-indentation))
719 (remainder (% indentation python-indent-offset))
720 (steps (/ (- indentation remainder) python-indent-offset)))
721 (setq python-indent-levels (list 0))
722 (dotimes (step steps)
723 (push (* python-indent-offset (1+ step)) python-indent-levels))
724 (when (not (eq 0 remainder))
725 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
726 (setq python-indent-levels (nreverse python-indent-levels))
727 (setq python-indent-current-level (1- (length python-indent-levels)))))
728
729 (defun python-indent-toggle-levels ()
730 "Toggle `python-indent-current-level' over `python-indent-levels'."
731 (setq python-indent-current-level (1- python-indent-current-level))
732 (when (< python-indent-current-level 0)
733 (setq python-indent-current-level (1- (length python-indent-levels)))))
734
735 (defun python-indent-line (&optional force-toggle)
736 "Internal implementation of `python-indent-line-function'.
737 Uses the offset calculated in
738 `python-indent-calculate-indentation' and available levels
739 indicated by the variable `python-indent-levels' to set the
740 current indentation.
741
742 When the variable `last-command' is equal to
743 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
744 levels indicated in the variable `python-indent-levels' by
745 setting the current level in the variable
746 `python-indent-current-level'.
747
748 When the variable `last-command' is not equal to
749 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
750 possible indentation levels and saves it in the variable
751 `python-indent-levels'. Afterwards it sets the variable
752 `python-indent-current-level' correctly so offset is equal
753 to (`nth' `python-indent-current-level' `python-indent-levels')"
754 (if (or (and (eq this-command 'indent-for-tab-command)
755 (eq last-command this-command))
756 force-toggle)
757 (if (not (equal python-indent-levels '(0)))
758 (python-indent-toggle-levels)
759 (python-indent-calculate-levels))
760 (python-indent-calculate-levels))
761 (beginning-of-line)
762 (delete-horizontal-space)
763 (indent-to (nth python-indent-current-level python-indent-levels))
764 (save-restriction
765 (widen)
766 (let ((closing-block-point (python-info-closing-block)))
767 (when closing-block-point
768 (message "Closes %s" (buffer-substring
769 closing-block-point
770 (save-excursion
771 (goto-char closing-block-point)
772 (line-end-position))))))))
773
774 (defun python-indent-line-function ()
775 "`indent-line-function' for Python mode.
776 See `python-indent-line' for details."
777 (python-indent-line))
778
779 (defun python-indent-dedent-line ()
780 "De-indent current line."
781 (interactive "*")
782 (when (and (not (or (python-info-ppss-context 'string)
783 (python-info-ppss-context 'comment)))
784 (<= (point-marker) (save-excursion
785 (back-to-indentation)
786 (point-marker)))
787 (> (current-column) 0))
788 (python-indent-line t)
789 t))
790
791 (defun python-indent-dedent-line-backspace (arg)
792 "De-indent current line.
793 Argument ARG is passed to `backward-delete-char-untabify' when
794 point is not in between the indentation."
795 (interactive "*p")
796 (when (not (python-indent-dedent-line))
797 (backward-delete-char-untabify arg)))
798 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
799
800 (defun python-indent-region (start end)
801 "Indent a python region automagically.
802
803 Called from a program, START and END specify the region to indent."
804 (let ((deactivate-mark nil))
805 (save-excursion
806 (goto-char end)
807 (setq end (point-marker))
808 (goto-char start)
809 (or (bolp) (forward-line 1))
810 (while (< (point) end)
811 (or (and (bolp) (eolp))
812 (let (word)
813 (forward-line -1)
814 (back-to-indentation)
815 (setq word (current-word))
816 (forward-line 1)
817 (when word
818 (beginning-of-line)
819 (delete-horizontal-space)
820 (indent-to (python-indent-calculate-indentation)))))
821 (forward-line 1))
822 (move-marker end nil))))
823
824 (defun python-indent-shift-left (start end &optional count)
825 "Shift lines contained in region START END by COUNT columns to the left.
826 COUNT defaults to `python-indent-offset'. If region isn't
827 active, the current line is shifted. The shifted region includes
828 the lines in which START and END lie. An error is signaled if
829 any lines in the region are indented less than COUNT columns."
830 (interactive
831 (if mark-active
832 (list (region-beginning) (region-end) current-prefix-arg)
833 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
834 (if count
835 (setq count (prefix-numeric-value count))
836 (setq count python-indent-offset))
837 (when (> count 0)
838 (let ((deactivate-mark nil))
839 (save-excursion
840 (goto-char start)
841 (while (< (point) end)
842 (if (and (< (current-indentation) count)
843 (not (looking-at "[ \t]*$")))
844 (error "Can't shift all lines enough"))
845 (forward-line))
846 (indent-rigidly start end (- count))))))
847
848 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
849
850 (defun python-indent-shift-right (start end &optional count)
851 "Shift lines contained in region START END by COUNT columns to the left.
852 COUNT defaults to `python-indent-offset'. If region isn't
853 active, the current line is shifted. The shifted region includes
854 the lines in which START and END lie."
855 (interactive
856 (if mark-active
857 (list (region-beginning) (region-end) current-prefix-arg)
858 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
859 (let ((deactivate-mark nil))
860 (if count
861 (setq count (prefix-numeric-value count))
862 (setq count python-indent-offset))
863 (indent-rigidly start end count)))
864
865 (defun python-indent-electric-colon (arg)
866 "Insert a colon and maybe de-indent the current line.
867 With numeric ARG, just insert that many colons. With
868 \\[universal-argument], just insert a single colon."
869 (interactive "*P")
870 (self-insert-command (if (not (integerp arg)) 1 arg))
871 (when (and (not arg)
872 (eolp)
873 (not (equal ?: (char-after (- (point-marker) 2))))
874 (not (or (python-info-ppss-context 'string)
875 (python-info-ppss-context 'comment))))
876 (let ((indentation (current-indentation))
877 (calculated-indentation (python-indent-calculate-indentation)))
878 (when (> indentation calculated-indentation)
879 (save-excursion
880 (indent-line-to calculated-indentation)
881 (when (not (python-info-closing-block))
882 (indent-line-to indentation)))))))
883 (put 'python-indent-electric-colon 'delete-selection t)
884
885 \f
886 ;;; Navigation
887
888 (defvar python-nav-beginning-of-defun-regexp
889 (python-rx line-start (* space) defun (+ space) (group symbol-name))
890 "Regular expresion matching beginning of class or function.
891 The name of the defun should be grouped so it can be retrieved
892 via `match-string'.")
893
894 (defun python-nav-beginning-of-defun (&optional nodecorators)
895 "Move point to `beginning-of-defun'.
896 When NODECORATORS is non-nil decorators are not included. This
897 is the main part of`python-beginning-of-defun-function'
898 implementation. Return non-nil if point is moved to the
899 `beginning-of-defun'."
900 (let ((indent-pos (save-excursion
901 (back-to-indentation)
902 (point-marker)))
903 (found)
904 (include-decorators
905 (lambda ()
906 (when (not nodecorators)
907 (when (save-excursion
908 (forward-line -1)
909 (looking-at (python-rx decorator)))
910 (while (and (not (bobp))
911 (forward-line -1)
912 (looking-at (python-rx decorator))))
913 (when (not (bobp)) (forward-line 1)))))))
914 (if (and (> (point) indent-pos)
915 (save-excursion
916 (goto-char (line-beginning-position))
917 (looking-at python-nav-beginning-of-defun-regexp)))
918 (progn
919 (goto-char (line-beginning-position))
920 (funcall include-decorators)
921 (setq found t))
922 (goto-char (line-beginning-position))
923 (when (re-search-backward python-nav-beginning-of-defun-regexp nil t)
924 (setq found t))
925 (goto-char (or (python-info-ppss-context 'string) (point)))
926 (funcall include-decorators))
927 found))
928
929 (defun python-beginning-of-defun-function (&optional arg nodecorators)
930 "Move point to the beginning of def or class.
931 With positive ARG move that number of functions forward. With
932 negative do the same but backwards. When NODECORATORS is non-nil
933 decorators are not included. Return non-nil if point is moved to the
934 `beginning-of-defun'."
935 (when (or (null arg) (= arg 0)) (setq arg 1))
936 (if (> arg 0)
937 (dotimes (i arg (python-nav-beginning-of-defun nodecorators)))
938 (let ((found))
939 (dotimes (i (- arg) found)
940 (python-end-of-defun-function)
941 (forward-comment 9999)
942 (goto-char (line-end-position))
943 (when (not (eobp))
944 (setq found
945 (python-nav-beginning-of-defun nodecorators)))))))
946
947 (defun python-end-of-defun-function ()
948 "Move point to the end of def or class.
949 Returns nil if point is not in a def or class."
950 (interactive)
951 (let ((beg-defun-indent)
952 (decorator-regexp "[[:space:]]*@"))
953 (when (looking-at decorator-regexp)
954 (while (and (not (eobp))
955 (forward-line 1)
956 (looking-at decorator-regexp))))
957 (when (not (looking-at python-nav-beginning-of-defun-regexp))
958 (python-beginning-of-defun-function))
959 (setq beg-defun-indent (current-indentation))
960 (forward-line 1)
961 (while (and (forward-line 1)
962 (not (eobp))
963 (or (not (current-word))
964 (> (current-indentation) beg-defun-indent))))
965 (forward-comment 9999)
966 (goto-char (line-beginning-position))))
967
968 (defun python-nav-sentence-start ()
969 "Move to start of current sentence."
970 (interactive "^")
971 (while (and (not (back-to-indentation))
972 (not (bobp))
973 (when (or
974 (save-excursion
975 (forward-line -1)
976 (python-info-line-ends-backslash-p))
977 (python-info-ppss-context 'string)
978 (python-info-ppss-context 'paren))
979 (forward-line -1)))))
980
981 (defun python-nav-sentence-end ()
982 "Move to end of current sentence."
983 (interactive "^")
984 (while (and (goto-char (line-end-position))
985 (not (eobp))
986 (when (or
987 (python-info-line-ends-backslash-p)
988 (python-info-ppss-context 'string)
989 (python-info-ppss-context 'paren))
990 (forward-line 1)))))
991
992 (defun python-nav-backward-sentence (&optional arg)
993 "Move backward to start of sentence. With ARG, do it arg times.
994 See `python-nav-forward-sentence' for more information."
995 (interactive "^p")
996 (or arg (setq arg 1))
997 (python-nav-forward-sentence (- arg)))
998
999 (defun python-nav-forward-sentence (&optional arg)
1000 "Move forward to next end of sentence. With ARG, repeat.
1001 With negative argument, move backward repeatedly to start of sentence."
1002 (interactive "^p")
1003 (or arg (setq arg 1))
1004 (while (> arg 0)
1005 (forward-comment 9999)
1006 (python-nav-sentence-end)
1007 (forward-line 1)
1008 (setq arg (1- arg)))
1009 (while (< arg 0)
1010 (python-nav-sentence-end)
1011 (forward-comment -9999)
1012 (python-nav-sentence-start)
1013 (forward-line -1)
1014 (setq arg (1+ arg))))
1015
1016 \f
1017 ;;; Shell integration
1018
1019 (defvar python-shell-buffer-name "Python"
1020 "Default buffer name for Python interpreter.")
1021
1022 (defcustom python-shell-interpreter "python"
1023 "Default Python interpreter for shell."
1024 :type 'string
1025 :group 'python
1026 :safe 'stringp)
1027
1028 (defvar python-shell-internal-buffer-name "Python Internal"
1029 "Default buffer name for the Internal Python interpreter.")
1030
1031 (defcustom python-shell-interpreter-args "-i"
1032 "Default arguments for the Python interpreter."
1033 :type 'string
1034 :group 'python
1035 :safe 'stringp)
1036
1037 (defcustom python-shell-prompt-regexp ">>> "
1038 "Regular Expression matching top\-level input prompt of python shell.
1039 It should not contain a caret (^) at the beginning."
1040 :type 'string
1041 :group 'python
1042 :safe 'stringp)
1043
1044 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1045 "Regular Expression matching block input prompt of python shell.
1046 It should not contain a caret (^) at the beginning."
1047 :type 'string
1048 :group 'python
1049 :safe 'stringp)
1050
1051 (defcustom python-shell-prompt-output-regexp nil
1052 "Regular Expression matching output prompt of python shell.
1053 It should not contain a caret (^) at the beginning."
1054 :type 'string
1055 :group 'python
1056 :safe 'stringp)
1057
1058 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1059 "Regular Expression matching pdb input prompt of python shell.
1060 It should not contain a caret (^) at the beginning."
1061 :type 'string
1062 :group 'python
1063 :safe 'stringp)
1064
1065 (defcustom python-shell-send-setup-max-wait 5
1066 "Seconds to wait for process output before code setup.
1067 If output is received before the especified time then control is
1068 returned in that moment and not after waiting."
1069 :type 'number
1070 :group 'python
1071 :safe 'numberp)
1072
1073 (defcustom python-shell-process-environment nil
1074 "List of enviroment variables for Python shell.
1075 This variable follows the same rules as `process-enviroment'
1076 since it merges with it before the process creation routines are
1077 called. When this variable is nil, the Python shell is run with
1078 the default `process-enviroment'."
1079 :type '(repeat string)
1080 :group 'python
1081 :safe 'listp)
1082
1083 (defcustom python-shell-exec-path nil
1084 "List of path to search for binaries.
1085 This variable follows the same rules as `exec-path' since it
1086 merges with it before the process creation routines are called.
1087 When this variable is nil, the Python shell is run with the
1088 default `exec-path'."
1089 :type '(repeat string)
1090 :group 'python
1091 :safe 'listp)
1092
1093 (defcustom python-shell-virtualenv-path nil
1094 "Path to virtualenv root.
1095 This variable, when set to a string, makes the values stored in
1096 `python-shell-process-environment' and `python-shell-exec-path'
1097 to be modified properly so shells are started with the specified
1098 virtualenv."
1099 :type 'string
1100 :group 'python
1101 :safe 'stringp)
1102
1103 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1104 python-ffap-setup-code
1105 python-eldoc-setup-code)
1106 "List of code run by `python-shell-send-setup-codes'.
1107 Each variable can contain either a simple string with the code to
1108 execute or a cons with the form (CODE . DESCRIPTION), where CODE
1109 is a string with the code to execute and DESCRIPTION is the
1110 description of it."
1111 :type '(repeat symbol)
1112 :group 'python
1113 :safe 'listp)
1114
1115 (defcustom python-shell-compilation-regexp-alist
1116 `((,(rx line-start (1+ (any " \t")) "File \""
1117 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1118 "\", line " (group (1+ digit)))
1119 1 2)
1120 (,(rx " in file " (group (1+ not-newline)) " on line "
1121 (group (1+ digit)))
1122 1 2)
1123 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1124 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1125 1 2))
1126 "`compilation-error-regexp-alist' for inferior Python."
1127 :type '(alist string)
1128 :group 'python)
1129
1130 (defun python-shell-get-process-name (dedicated)
1131 "Calculate the appropiate process name for inferior Python process.
1132 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1133 returns a string with the form
1134 `python-shell-buffer-name'[variable `buffer-file-name'] else
1135 returns the value of `python-shell-buffer-name'. After
1136 calculating the process name adds the buffer name for the process
1137 in the `same-window-buffer-names' list."
1138 (let ((process-name
1139 (if (and dedicated
1140 buffer-file-name)
1141 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1142 (format "%s" python-shell-buffer-name))))
1143 (add-to-list 'same-window-buffer-names (purecopy
1144 (format "*%s*" process-name)))
1145 process-name))
1146
1147 (defun python-shell-internal-get-process-name ()
1148 "Calculate the appropiate process name for Internal Python process.
1149 The name is calculated from `python-shell-global-buffer-name' and
1150 a hash of all relevant global shell settings in order to ensure
1151 uniqueness for different types of configurations."
1152 (format "%s [%s]"
1153 python-shell-internal-buffer-name
1154 (md5
1155 (concat
1156 (python-shell-parse-command)
1157 (mapconcat #'symbol-value python-shell-setup-codes "")
1158 (mapconcat #'indentity python-shell-process-environment "")
1159 (or python-shell-virtualenv-path "")
1160 (mapconcat #'indentity python-shell-exec-path "")))))
1161
1162 (defun python-shell-parse-command ()
1163 "Calculate the string used to execute the inferior Python process."
1164 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1165
1166 (defun python-shell-calculate-process-enviroment ()
1167 "Calculate process enviroment given `python-shell-virtualenv-path'."
1168 (let ((env (python-util-merge 'list python-shell-process-environment
1169 process-environment 'string=))
1170 (virtualenv (if python-shell-virtualenv-path
1171 (directory-file-name python-shell-virtualenv-path)
1172 nil)))
1173 (if (not virtualenv)
1174 env
1175 (dolist (envvar env)
1176 (let* ((split (split-string envvar "=" t))
1177 (name (nth 0 split))
1178 (value (nth 1 split)))
1179 (when (not (string= name "PYTHONHOME"))
1180 (when (string= name "PATH")
1181 (setq value (format "%s/bin:%s" virtualenv value)))
1182 (setq env (cons (format "%s=%s" name value) env)))))
1183 (cons (format "VIRTUAL_ENV=%s" virtualenv) env))))
1184
1185 (defun python-shell-calculate-exec-path ()
1186 "Calculate exec path given `python-shell-virtualenv-path'."
1187 (let ((path (python-util-merge 'list python-shell-exec-path
1188 exec-path 'string=)))
1189 (if (not python-shell-virtualenv-path)
1190 path
1191 (cons (format "%s/bin"
1192 (directory-file-name python-shell-virtualenv-path))
1193 path))))
1194
1195 (defun python-comint-output-filter-function (output)
1196 "Hook run after content is put into comint buffer.
1197 OUTPUT is a string with the contents of the buffer."
1198 (ansi-color-filter-apply output))
1199
1200 (defvar inferior-python-mode-current-file nil
1201 "Current file from which a region was sent.")
1202 (make-variable-buffer-local 'inferior-python-mode-current-file)
1203
1204 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1205 "Major mode for Python inferior process.
1206 Runs a Python interpreter as a subprocess of Emacs, with Python
1207 I/O through an Emacs buffer. Variables
1208 `python-shell-interpreter' and `python-shell-interpreter-args'
1209 controls which Python interpreter is run. Variables
1210 `python-shell-prompt-regexp',
1211 `python-shell-prompt-output-regexp',
1212 `python-shell-prompt-block-regexp',
1213 `python-shell-completion-setup-code',
1214 `python-shell-completion-string-code', `python-eldoc-setup-code',
1215 `python-eldoc-string-code', `python-ffap-setup-code' and
1216 `python-ffap-string-code' can customize this mode for different
1217 Python interpreters.
1218
1219 You can also add additional setup code to be run at
1220 initialization of the interpreter via `python-shell-setup-codes'
1221 variable.
1222
1223 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1224 (set-syntax-table python-mode-syntax-table)
1225 (setq mode-line-process '(":%s"))
1226 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1227 python-shell-prompt-regexp
1228 python-shell-prompt-block-regexp
1229 python-shell-prompt-pdb-regexp))
1230 (make-local-variable 'comint-output-filter-functions)
1231 (add-hook 'comint-output-filter-functions
1232 'python-comint-output-filter-function)
1233 (add-hook 'comint-output-filter-functions
1234 'python-pdbtrack-comint-output-filter-function)
1235 (set (make-local-variable 'compilation-error-regexp-alist)
1236 python-shell-compilation-regexp-alist)
1237 (define-key inferior-python-mode-map [remap complete-symbol]
1238 'completion-at-point)
1239 (add-hook 'completion-at-point-functions
1240 'python-shell-completion-complete-at-point nil 'local)
1241 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1242 'python-shell-completion-complete-at-point)
1243 (define-key inferior-python-mode-map (kbd "<tab>")
1244 'python-shell-completion-complete-or-indent)
1245 (compilation-shell-minor-mode 1))
1246
1247 (defun run-python (dedicated cmd)
1248 "Run an inferior Python process.
1249 Input and output via buffer named after
1250 `python-shell-buffer-name'. If there is a process already
1251 running in that buffer, just switch to it.
1252 With argument, allows you to define DEDICATED, so a dedicated
1253 process for the current buffer is open, and define CMD so you can
1254 edit the command used to call the interpreter (default is value
1255 of `python-shell-interpreter' and arguments defined in
1256 `python-shell-interpreter-args'). Runs the hook
1257 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1258 run).
1259 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1260 (interactive
1261 (if current-prefix-arg
1262 (list
1263 (y-or-n-p "Make dedicated process? ")
1264 (read-string "Run Python: " (python-shell-parse-command)))
1265 (list nil (python-shell-parse-command))))
1266 (let* ((proc-name (python-shell-get-process-name dedicated))
1267 (proc-buffer-name (format "*%s*" proc-name))
1268 (process-environment (python-shell-calculate-process-enviroment))
1269 (exec-path (python-shell-calculate-exec-path)))
1270 (when (not (comint-check-proc proc-buffer-name))
1271 (let ((cmdlist (split-string-and-unquote cmd)))
1272 (set-buffer
1273 (apply 'make-comint proc-name (car cmdlist) nil
1274 (cdr cmdlist)))
1275 (inferior-python-mode)))
1276 (pop-to-buffer proc-buffer-name))
1277 dedicated)
1278
1279 (defun run-python-internal ()
1280 "Run an inferior Internal Python process.
1281 Input and output via buffer named after
1282 `python-shell-internal-buffer-name' and what
1283 `python-shell-internal-get-process-name' returns. This new kind
1284 of shell is intended to be used for generic communication related
1285 to defined configurations. The main difference with global or
1286 dedicated shells is that these ones are attached to a
1287 configuration, not a buffer. This means that can be used for
1288 example to retrieve the sys.path and other stuff, without messing
1289 with user shells. Runs the hook
1290 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1291 run). \(Type \\[describe-mode] in the process buffer for a list
1292 of commands.)"
1293 (interactive)
1294 (save-excursion
1295 (let* ((cmd (python-shell-parse-command))
1296 (proc-name (python-shell-internal-get-process-name))
1297 (proc-buffer-name (format "*%s*" proc-name))
1298 (process-environment (python-shell-calculate-process-enviroment))
1299 (exec-path (python-shell-calculate-exec-path)))
1300 (when (not (comint-check-proc proc-buffer-name))
1301 (let ((cmdlist (split-string-and-unquote cmd)))
1302 (set-buffer
1303 (apply 'make-comint proc-name (car cmdlist) nil
1304 (cdr cmdlist)))
1305 (inferior-python-mode))))))
1306
1307 (defun python-shell-get-process ()
1308 "Get inferior Python process for current buffer and return it."
1309 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1310 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1311 (global-proc-name (python-shell-get-process-name nil))
1312 (global-proc-buffer-name (format "*%s*" global-proc-name))
1313 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1314 (global-running (comint-check-proc global-proc-buffer-name)))
1315 ;; Always prefer dedicated
1316 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1317 (and global-running global-proc-buffer-name)))))
1318
1319 (defun python-shell-get-or-create-process ()
1320 "Get or create an inferior Python process for current buffer and return it."
1321 (let* ((old-buffer (current-buffer))
1322 (dedicated-proc-name (python-shell-get-process-name t))
1323 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1324 (global-proc-name (python-shell-get-process-name nil))
1325 (global-proc-buffer-name (format "*%s*" global-proc-name))
1326 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1327 (global-running (comint-check-proc global-proc-buffer-name))
1328 (current-prefix-arg 4))
1329 (when (and (not dedicated-running) (not global-running))
1330 (if (call-interactively 'run-python)
1331 (setq dedicated-running t)
1332 (setq global-running t)))
1333 ;; Always prefer dedicated
1334 (switch-to-buffer old-buffer)
1335 (get-buffer-process (if dedicated-running
1336 dedicated-proc-buffer-name
1337 global-proc-buffer-name))))
1338
1339 (defun python-shell-internal-get-or-create-process ()
1340 "Get or create an inferior Internal Python process."
1341 (let* ((proc-name (python-shell-internal-get-process-name))
1342 (proc-buffer-name (format "*%s*" proc-name)))
1343 (run-python-internal)
1344 (get-buffer-process proc-buffer-name)))
1345
1346 (defun python-shell-send-string (string &optional process msg)
1347 "Send STRING to inferior Python PROCESS.
1348 When MSG is non-nil messages the first line of STRING."
1349 (interactive "sPython command: ")
1350 (let ((process (or process (python-shell-get-or-create-process)))
1351 (lines (split-string string "\n" t)))
1352 (when msg
1353 (message (format "Sent: %s..." (nth 0 lines))))
1354 (if (> (length lines) 1)
1355 (let* ((temp-file-name (make-temp-file "py"))
1356 (file-name (or (buffer-file-name) temp-file-name)))
1357 (with-temp-file temp-file-name
1358 (insert string)
1359 (delete-trailing-whitespace))
1360 (python-shell-send-file file-name process temp-file-name))
1361 (comint-send-string process string)
1362 (when (or (not (string-match "\n$" string))
1363 (string-match "\n[ \t].*\n?$" string))
1364 (comint-send-string process "\n")))))
1365
1366 (defun python-shell-send-string-no-output (string &optional process msg)
1367 "Send STRING to PROCESS and inhibit output.
1368 When MSG is non-nil messages the first line of STRING. Return
1369 the output."
1370 (let* ((output-buffer)
1371 (process (or process (python-shell-get-or-create-process)))
1372 (comint-preoutput-filter-functions
1373 (append comint-preoutput-filter-functions
1374 '(ansi-color-filter-apply
1375 (lambda (string)
1376 (setq output-buffer (concat output-buffer string))
1377 "")))))
1378 (python-shell-send-string string process msg)
1379 (accept-process-output process)
1380 ;; Cleanup output prompt regexp
1381 (when (and (not (string= "" output-buffer))
1382 (> (length python-shell-prompt-output-regexp) 0))
1383 (setq output-buffer
1384 (with-temp-buffer
1385 (insert output-buffer)
1386 (goto-char (point-min))
1387 (forward-comment 9999)
1388 (buffer-substring-no-properties
1389 (or
1390 (and (looking-at python-shell-prompt-output-regexp)
1391 (re-search-forward
1392 python-shell-prompt-output-regexp nil t 1))
1393 (point-marker))
1394 (point-max)))))
1395 (mapconcat
1396 (lambda (string) string)
1397 (butlast (split-string output-buffer "\n")) "\n")))
1398
1399 (defun python-shell-internal-send-string (string)
1400 "Send STRING to the Internal Python interpreter.
1401 Returns the output. See `python-shell-send-string-no-output'."
1402 (python-shell-send-string-no-output
1403 ;; Makes this function compatible with the old
1404 ;; python-send-receive. (At least for CEDET).
1405 (replace-regexp-in-string "_emacs_out +" "" string)
1406 (python-shell-internal-get-or-create-process) nil))
1407
1408 (define-obsolete-function-alias
1409 'python-send-receive 'python-shell-internal-send-string "23.3"
1410 "Send STRING to inferior Python (if any) and return result.
1411 The result is what follows `_emacs_out' in the output.
1412 This is a no-op if `python-check-comint-prompt' returns nil.")
1413
1414 (defun python-shell-send-region (start end)
1415 "Send the region delimited by START and END to inferior Python process."
1416 (interactive "r")
1417 (let ((deactivate-mark nil))
1418 (python-shell-send-string (buffer-substring start end) nil t)))
1419
1420 (defun python-shell-send-buffer ()
1421 "Send the entire buffer to inferior Python process."
1422 (interactive)
1423 (save-restriction
1424 (widen)
1425 (python-shell-send-region (point-min) (point-max))))
1426
1427 (defun python-shell-send-defun (arg)
1428 "Send the current defun to inferior Python process.
1429 When argument ARG is non-nil sends the innermost defun."
1430 (interactive "P")
1431 (save-excursion
1432 (python-shell-send-region
1433 (progn
1434 (or (python-beginning-of-defun-function)
1435 (progn (beginning-of-line) (point-marker))))
1436 (progn
1437 (or (python-end-of-defun-function)
1438 (progn (end-of-line) (point-marker)))))))
1439
1440 (defun python-shell-send-file (file-name &optional process temp-file-name)
1441 "Send FILE-NAME to inferior Python PROCESS.
1442 If TEMP-FILE-NAME is passed then that file is used for processing
1443 instead, while internally the shell will continue to use
1444 FILE-NAME."
1445 (interactive "fFile to send: ")
1446 (let* ((process (or process (python-shell-get-or-create-process)))
1447 (temp-file-name (when temp-file-name
1448 (expand-file-name temp-file-name)))
1449 (file-name (or (expand-file-name file-name) temp-file-name)))
1450 (when (not file-name)
1451 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1452 (with-current-buffer (process-buffer process)
1453 (setq inferior-python-mode-current-file
1454 (convert-standard-filename file-name)))
1455 (python-shell-send-string
1456 (format
1457 (concat "__pyfile = open('''%s''');"
1458 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1459 "__pyfile.close()")
1460 (or temp-file-name file-name) file-name)
1461 process)))
1462
1463 (defun python-shell-switch-to-shell ()
1464 "Switch to inferior Python process buffer."
1465 (interactive)
1466 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1467
1468 (defun python-shell-send-setup-code ()
1469 "Send all setup code for shell.
1470 This function takes the list of setup code to send from the
1471 `python-shell-setup-codes' list."
1472 (let ((msg "Sent %s")
1473 (process (get-buffer-process (current-buffer))))
1474 (accept-process-output process python-shell-send-setup-max-wait)
1475 (dolist (code python-shell-setup-codes)
1476 (when code
1477 (when (consp code)
1478 (setq msg (cdr code)))
1479 (message (format msg code))
1480 (python-shell-send-string-no-output
1481 (symbol-value code) process)))))
1482
1483 (add-hook 'inferior-python-mode-hook
1484 #'python-shell-send-setup-code)
1485
1486 \f
1487 ;;; Shell completion
1488
1489 (defvar python-shell-completion-setup-code
1490 "try:
1491 import readline
1492 except ImportError:
1493 def __COMPLETER_all_completions(text): []
1494 else:
1495 import rlcompleter
1496 readline.set_completer(rlcompleter.Completer().complete)
1497 def __COMPLETER_all_completions(text):
1498 import sys
1499 completions = []
1500 try:
1501 i = 0
1502 while True:
1503 res = readline.get_completer()(text, i)
1504 if not res: break
1505 i += 1
1506 completions.append(res)
1507 except NameError:
1508 pass
1509 return completions"
1510 "Code used to setup completion in inferior Python processes.")
1511
1512 (defvar python-shell-completion-string-code
1513 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1514 "Python code used to get a string of completions separated by semicolons.")
1515
1516 (defun python-shell-completion--get-completions (input process)
1517 "Retrieve available completions for INPUT using PROCESS."
1518 (with-current-buffer (process-buffer process)
1519 (let ((completions (python-shell-send-string-no-output
1520 (format python-shell-completion-string-code input)
1521 process)))
1522 (when (> (length completions) 2)
1523 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
1524
1525 (defun python-shell-completion--get-completion (input completions)
1526 "Get completion for INPUT using COMPLETIONS."
1527 (let ((completion (when completions
1528 (try-completion input completions))))
1529 (cond ((eq completion t)
1530 input)
1531 ((null completion)
1532 (message "Can't find completion for \"%s\"" input)
1533 (ding)
1534 input)
1535 ((not (string= input completion))
1536 completion)
1537 (t
1538 (message "Making completion list...")
1539 (with-output-to-temp-buffer "*Python Completions*"
1540 (display-completion-list
1541 (all-completions input completions)))
1542 input))))
1543
1544 (defun python-shell-completion-complete-at-point ()
1545 "Perform completion at point in inferior Python process."
1546 (interactive)
1547 (with-syntax-table python-dotty-syntax-table
1548 (when (and comint-last-prompt-overlay
1549 (> (point-marker) (overlay-end comint-last-prompt-overlay)))
1550 (let* ((process (get-buffer-process (current-buffer)))
1551 (input (substring-no-properties
1552 (or (comint-word (current-word)) "") nil nil)))
1553 (delete-char (- (length input)))
1554 (insert
1555 (python-shell-completion--get-completion
1556 input (python-shell-completion--get-completions input process)))))))
1557
1558 (defun python-shell-completion-complete-or-indent ()
1559 "Complete or indent depending on the context.
1560 If content before pointer is all whitespace indent. If not try
1561 to complete."
1562 (interactive)
1563 (if (string-match "^[[:space:]]*$"
1564 (buffer-substring (comint-line-beginning-position)
1565 (point-marker)))
1566 (indent-for-tab-command)
1567 (comint-dynamic-complete)))
1568
1569 \f
1570 ;;; PDB Track integration
1571
1572 (defvar python-pdbtrack-stacktrace-info-regexp
1573 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1574 "Regular Expression matching stacktrace information.
1575 Used to extract the current line and module beign inspected. The
1576 regexp should not start with a caret (^) and can contain a string
1577 placeholder (\%s) which is replaced with the filename beign
1578 inspected (so other files in the debugging process are not
1579 opened)")
1580
1581 (defvar python-pdbtrack-tracking-buffers '()
1582 "Alist containing elements of form (#<buffer> . #<buffer>).
1583 The car of each element of the alist is the tracking buffer and
1584 the cdr is the tracked buffer.")
1585
1586 (defun python-pdbtrack-get-or-add-tracking-buffers ()
1587 "Get/Add a tracked buffer for the current buffer.
1588 Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1589 Returns a cons with the form:
1590 * (#<tracking buffer> . #< tracked buffer>)."
1591 (or
1592 (assq (current-buffer) python-pdbtrack-tracking-buffers)
1593 (let* ((file (with-current-buffer (current-buffer)
1594 inferior-python-mode-current-file))
1595 (tracking-buffers
1596 `(,(current-buffer) .
1597 ,(or (get-file-buffer file)
1598 (find-file-noselect file)))))
1599 (set-buffer (cdr tracking-buffers))
1600 (python-mode)
1601 (set-buffer (car tracking-buffers))
1602 (setq python-pdbtrack-tracking-buffers
1603 (cons tracking-buffers python-pdbtrack-tracking-buffers))
1604 tracking-buffers)))
1605
1606 (defun python-pdbtrack-comint-output-filter-function (output)
1607 "Move overlay arrow to current pdb line in tracked buffer.
1608 Argument OUTPUT is a string with the output from the comint process."
1609 (when (not (string= output ""))
1610 (let ((full-output (ansi-color-filter-apply
1611 (buffer-substring comint-last-input-end
1612 (point-max)))))
1613 (if (string-match python-shell-prompt-pdb-regexp full-output)
1614 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1615 (line-num
1616 (save-excursion
1617 (string-match
1618 (format python-pdbtrack-stacktrace-info-regexp
1619 (regexp-quote
1620 inferior-python-mode-current-file))
1621 full-output)
1622 (string-to-number (or (match-string-no-properties 1 full-output) ""))))
1623 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers)))
1624 (tracked-buffer-line-pos))
1625 (when line-num
1626 (with-current-buffer (cdr tracking-buffers)
1627 (set (make-local-variable 'overlay-arrow-string) "=>")
1628 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1629 (setq tracked-buffer-line-pos (progn
1630 (goto-char (point-min))
1631 (forward-line (1- line-num))
1632 (point-marker)))
1633 (when tracked-buffer-window
1634 (set-window-point tracked-buffer-window tracked-buffer-line-pos))
1635 (set-marker overlay-arrow-position tracked-buffer-line-pos)))
1636 (pop-to-buffer (cdr tracking-buffers))
1637 (switch-to-buffer-other-window (car tracking-buffers)))
1638 (let ((tracking-buffers (assq (current-buffer)
1639 python-pdbtrack-tracking-buffers)))
1640 (when tracking-buffers
1641 (if inferior-python-mode-current-file
1642 (with-current-buffer (cdr tracking-buffers)
1643 (set-marker overlay-arrow-position nil))
1644 (kill-buffer (cdr tracking-buffers)))
1645 (setq python-pdbtrack-tracking-buffers
1646 (assq-delete-all (current-buffer)
1647 python-pdbtrack-tracking-buffers)))))))
1648 output)
1649
1650 \f
1651 ;;; Symbol completion
1652
1653 (defun python-completion-complete-at-point ()
1654 "Complete current symbol at point.
1655 For this to work the best as possible you should call
1656 `python-shell-send-buffer' from time to time so context in
1657 inferior python process is updated properly."
1658 (interactive)
1659 (let ((process (python-shell-get-process)))
1660 (if (not process)
1661 (error "Completion needs an inferior Python process running")
1662 (with-syntax-table python-dotty-syntax-table
1663 (let* ((input (substring-no-properties
1664 (or (comint-word (current-word)) "") nil nil))
1665 (completions (python-shell-completion--get-completions
1666 input process)))
1667 (delete-char (- (length input)))
1668 (insert
1669 (python-shell-completion--get-completion
1670 input completions)))))))
1671
1672 (add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.")
1673
1674 \f
1675 ;;; Fill paragraph
1676
1677 (defcustom python-fill-comment-function 'python-fill-comment
1678 "Function to fill comments.
1679 This is the function used by `python-fill-paragraph-function' to
1680 fill comments."
1681 :type 'symbol
1682 :group 'python
1683 :safe 'symbolp)
1684
1685 (defcustom python-fill-string-function 'python-fill-string
1686 "Function to fill strings.
1687 This is the function used by `python-fill-paragraph-function' to
1688 fill strings."
1689 :type 'symbol
1690 :group 'python
1691 :safe 'symbolp)
1692
1693 (defcustom python-fill-decorator-function 'python-fill-decorator
1694 "Function to fill decorators.
1695 This is the function used by `python-fill-paragraph-function' to
1696 fill decorators."
1697 :type 'symbol
1698 :group 'python
1699 :safe 'symbolp)
1700
1701 (defcustom python-fill-paren-function 'python-fill-paren
1702 "Function to fill parens.
1703 This is the function used by `python-fill-paragraph-function' to
1704 fill parens."
1705 :type 'symbol
1706 :group 'python
1707 :safe 'symbolp)
1708
1709 (defun python-fill-paragraph-function (&optional justify)
1710 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1711 If any of the current line is in or at the end of a multi-line string,
1712 fill the string or the paragraph of it that point is in, preserving
1713 the string's indentation.
1714 Optional argument JUSTIFY defines if the paragraph should be justified."
1715 (interactive "P")
1716 (save-excursion
1717 (back-to-indentation)
1718 (cond
1719 ;; Comments
1720 ((funcall python-fill-comment-function justify))
1721 ;; Strings/Docstrings
1722 ((save-excursion (skip-chars-forward "\"'uUrR")
1723 (python-info-ppss-context 'string))
1724 (funcall python-fill-string-function justify))
1725 ;; Decorators
1726 ((equal (char-after (save-excursion
1727 (back-to-indentation)
1728 (point-marker))) ?@)
1729 (funcall python-fill-decorator-function justify))
1730 ;; Parens
1731 ((or (python-info-ppss-context 'paren)
1732 (looking-at (python-rx open-paren))
1733 (save-excursion
1734 (skip-syntax-forward "^(" (line-end-position))
1735 (looking-at (python-rx open-paren))))
1736 (funcall python-fill-paren-function justify))
1737 (t t))))
1738
1739 (defun python-fill-comment (&optional justify)
1740 "Comment fill function for `python-fill-paragraph-function'.
1741 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1742 (fill-comment-paragraph justify))
1743
1744 (defun python-fill-string (&optional justify)
1745 "String fill function for `python-fill-paragraph-function'.
1746 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1747 (let ((marker (point-marker))
1748 (string-start-marker
1749 (progn
1750 (skip-chars-forward "\"'uUrR")
1751 (goto-char (python-info-ppss-context 'string))
1752 (skip-chars-forward "\"'uUrR")
1753 (point-marker)))
1754 (reg-start (line-beginning-position))
1755 (string-end-marker
1756 (progn
1757 (while (python-info-ppss-context 'string)
1758 (goto-char (1+ (point-marker))))
1759 (skip-chars-backward "\"'")
1760 (point-marker)))
1761 (reg-end (line-end-position))
1762 (fill-paragraph-function))
1763 (save-restriction
1764 (narrow-to-region reg-start reg-end)
1765 (save-excursion
1766 (goto-char string-start-marker)
1767 (delete-region (point-marker) (progn
1768 (skip-syntax-forward "> ")
1769 (point-marker)))
1770 (goto-char string-end-marker)
1771 (delete-region (point-marker) (progn
1772 (skip-syntax-backward "> ")
1773 (point-marker)))
1774 (save-excursion
1775 (goto-char marker)
1776 (fill-paragraph justify))
1777 ;; If there is a newline in the docstring lets put triple
1778 ;; quote in it's own line to follow pep 8
1779 (when (save-excursion
1780 (re-search-backward "\n" string-start-marker t))
1781 (newline)
1782 (newline-and-indent))
1783 (fill-paragraph justify)))) t)
1784
1785 (defun python-fill-decorator (&optional justify)
1786 "Decorator fill function for `python-fill-paragraph-function'.
1787 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1788 t)
1789
1790 (defun python-fill-paren (&optional justify)
1791 "Paren fill function for `python-fill-paragraph-function'.
1792 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1793 (save-restriction
1794 (narrow-to-region (progn
1795 (while (python-info-ppss-context 'paren)
1796 (goto-char (1- (point-marker))))
1797 (point-marker)
1798 (line-beginning-position))
1799 (progn
1800 (when (not (python-info-ppss-context 'paren))
1801 (end-of-line)
1802 (when (not (python-info-ppss-context 'paren))
1803 (skip-syntax-backward "^)")))
1804 (while (python-info-ppss-context 'paren)
1805 (goto-char (1+ (point-marker))))
1806 (point-marker)))
1807 (let ((paragraph-start "\f\\|[ \t]*$")
1808 (paragraph-separate ",")
1809 (fill-paragraph-function))
1810 (goto-char (point-min))
1811 (fill-paragraph justify))
1812 (while (not (eobp))
1813 (forward-line 1)
1814 (python-indent-line)
1815 (goto-char (line-end-position)))) t)
1816
1817 \f
1818 ;;; Skeletons
1819
1820 (defcustom python-skeleton-autoinsert nil
1821 "Non-nil means template skeletons will be automagically inserted.
1822 This happens when pressing \"if<SPACE>\", for example, to prompt for
1823 the if condition."
1824 :type 'boolean
1825 :group 'python)
1826
1827 (defvar python-skeleton-available '()
1828 "Internal list of available skeletons.")
1829 (make-variable-buffer-local 'inferior-python-mode-current-file)
1830
1831 (define-abbrev-table 'python-mode-abbrev-table ()
1832 "Abbrev table for Python mode."
1833 :case-fixed t
1834 ;; Allow / inside abbrevs.
1835 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1836 ;; Only expand in code.
1837 :enable-function (lambda ()
1838 (and
1839 (not (or (python-info-ppss-context 'string)
1840 (python-info-ppss-context 'comment)))
1841 python-skeleton-autoinsert)))
1842
1843 (defmacro python-skeleton-define (name doc &rest skel)
1844 "Define a `python-mode' skeleton using NAME DOC and SKEL.
1845 The skeleton will be bound to python-skeleton-NAME and will
1846 be added to `python-mode-abbrev-table'."
1847 (let* ((name (symbol-name name))
1848 (function-name (intern (concat "python-skeleton-" name))))
1849 `(progn
1850 (define-abbrev python-mode-abbrev-table ,name "" ',function-name)
1851 (setq python-skeleton-available
1852 (cons ',function-name python-skeleton-available))
1853 (define-skeleton ,function-name
1854 ,(or doc
1855 (format "Insert %s statement." name))
1856 ,@skel))))
1857 (put 'python-skeleton-define 'lisp-indent-function 2)
1858
1859 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
1860 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
1861 The skeleton will be bound to python-skeleton-NAME."
1862 (let* ((name (symbol-name name))
1863 (function-name (intern (concat "python-skeleton--" name)))
1864 (msg (format
1865 "Add '%s' clause? " name)))
1866 (when (not skel)
1867 (setq skel
1868 `(< ,(format "%s:" name) \n \n
1869 > _ \n)))
1870 `(define-skeleton ,function-name
1871 ,(or doc
1872 (format "Auxiliary skeleton for %s statement." name))
1873 nil
1874 (unless (y-or-n-p ,msg)
1875 (signal 'quit t))
1876 ,@skel)))
1877 (put 'python-define-auxiliary-skeleton 'lisp-indent-function 2)
1878
1879 (python-define-auxiliary-skeleton else nil)
1880
1881 (python-define-auxiliary-skeleton except nil)
1882
1883 (python-define-auxiliary-skeleton finally nil)
1884
1885 (python-skeleton-define if nil
1886 "Condition: "
1887 "if " str ":" \n
1888 _ \n
1889 ("other condition, %s: "
1890 <
1891 "elif " str ":" \n
1892 > _ \n nil)
1893 '(python-skeleton--else) | ^)
1894
1895 (python-skeleton-define while nil
1896 "Condition: "
1897 "while " str ":" \n
1898 > _ \n
1899 '(python-skeleton--else) | ^)
1900
1901 (python-skeleton-define for nil
1902 "Iteration spec: "
1903 "for " str ":" \n
1904 > _ \n
1905 '(python-skeleton--else) | ^)
1906
1907 (python-skeleton-define try nil
1908 nil
1909 "try:" \n
1910 > _ \n
1911 ("Exception, %s: "
1912 <
1913 "except " str ":" \n
1914 > _ \n nil)
1915 resume:
1916 '(python-skeleton--except)
1917 '(python-skeleton--else)
1918 '(python-skeleton--finally) | ^)
1919
1920 (python-skeleton-define def nil
1921 "Function name: "
1922 "def " str " (" ("Parameter, %s: "
1923 (unless (equal ?\( (char-before)) ", ")
1924 str) "):" \n
1925 "\"\"\"" - "\"\"\"" \n
1926 > _ \n)
1927
1928 (python-skeleton-define class nil
1929 "Class name: "
1930 "class " str " (" ("Inheritance, %s: "
1931 (unless (equal ?\( (char-before)) ", ")
1932 str)
1933 & ")" | -2
1934 ":" \n
1935 "\"\"\"" - "\"\"\"" \n
1936 > _ \n)
1937
1938 (defun python-skeleton-add-menu-items ()
1939 "Add menu items to Python->Skeletons menu."
1940 (let ((skeletons (sort python-skeleton-available 'string<))
1941 (items))
1942 (dolist (skeleton skeletons)
1943 (easy-menu-add-item
1944 nil '("Python" "Skeletons")
1945 `[,(format
1946 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
1947 ,skeleton t]))))
1948 \f
1949 ;;; FFAP
1950
1951 (defvar python-ffap-setup-code
1952 "def __FFAP_get_module_path(module):
1953 try:
1954 import os
1955 path = __import__(module).__file__
1956 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
1957 path = path[:-1]
1958 return path
1959 except:
1960 return ''"
1961 "Python code to get a module path.")
1962
1963 (defvar python-ffap-string-code
1964 "__FFAP_get_module_path('''%s''')\n"
1965 "Python code used to get a string with the path of a module.")
1966
1967 (defun python-ffap-module-path (module)
1968 "Function for `ffap-alist' to return path for MODULE."
1969 (let ((process (or
1970 (and (eq major-mode 'inferior-python-mode)
1971 (get-buffer-process (current-buffer)))
1972 (python-shell-get-process))))
1973 (if (not process)
1974 nil
1975 (let ((module-file
1976 (python-shell-send-string-no-output
1977 (format python-ffap-string-code module) process)))
1978 (when module-file
1979 (substring-no-properties module-file 1 -1))))))
1980
1981 (eval-after-load "ffap"
1982 '(progn
1983 (push '(python-mode . python-ffap-module-path) ffap-alist)
1984 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
1985
1986 \f
1987 ;;; Code check
1988
1989 (defvar python-check-command
1990 "pychecker --stdlib"
1991 "Command used to check a Python file.")
1992
1993 (defvar python-check-custom-command nil
1994 "Internal use.")
1995
1996 (defun python-check (command)
1997 "Check a Python file (default current buffer's file).
1998 Runs COMMAND, a shell command, as if by `compile'. See
1999 `python-check-command' for the default."
2000 (interactive
2001 (list (read-string "Check command: "
2002 (or python-check-custom-command
2003 (concat python-check-command " "
2004 (shell-quote-argument
2005 (or
2006 (let ((name (buffer-file-name)))
2007 (and name
2008 (file-name-nondirectory name)))
2009 "")))))))
2010 (setq python-check-custom-command command)
2011 (save-some-buffers (not compilation-ask-about-save) nil)
2012 (compilation-start command))
2013
2014 \f
2015 ;;; Eldoc
2016
2017 (defvar python-eldoc-setup-code
2018 "def __PYDOC_get_help(obj):
2019 try:
2020 import inspect
2021 if hasattr(obj, 'startswith'):
2022 obj = eval(obj, globals())
2023 doc = inspect.getdoc(obj)
2024 if not doc and callable(obj):
2025 target = None
2026 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2027 target = obj.__init__
2028 objtype = 'class'
2029 else:
2030 target = obj
2031 objtype = 'def'
2032 if target:
2033 args = inspect.formatargspec(
2034 *inspect.getargspec(target)
2035 )
2036 name = obj.__name__
2037 doc = '{objtype} {name}{args}'.format(
2038 objtype=objtype, name=name, args=args
2039 )
2040 else:
2041 doc = doc.splitlines()[0]
2042 except:
2043 doc = ''
2044 try:
2045 exec('print doc')
2046 except SyntaxError:
2047 print(doc)"
2048 "Python code to setup documentation retrieval.")
2049
2050 (defvar python-eldoc-string-code
2051 "__PYDOC_get_help('''%s''')\n"
2052 "Python code used to get a string with the documentation of an object.")
2053
2054 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
2055 "Internal implementation to get documentation at point.
2056 If not FORCE-INPUT is passed then what `current-word' returns
2057 will be used. If not FORCE-PROCESS is passed what
2058 `python-shell-get-process' returns is used."
2059 (let ((process (or force-process (python-shell-get-process))))
2060 (if (not process)
2061 "Eldoc needs an inferior Python process running."
2062 (let* ((current-defun (python-info-current-defun))
2063 (input (or force-input
2064 (with-syntax-table python-dotty-syntax-table
2065 (if (not current-defun)
2066 (current-word)
2067 (concat current-defun "." (current-word))))))
2068 (ppss (syntax-ppss))
2069 (help (when (and input
2070 (not (string= input (concat current-defun ".")))
2071 (not (or (python-info-ppss-context 'string ppss)
2072 (python-info-ppss-context 'comment ppss))))
2073 (when (string-match (concat
2074 (regexp-quote (concat current-defun "."))
2075 "self\\.") input)
2076 (with-temp-buffer
2077 (insert input)
2078 (goto-char (point-min))
2079 (forward-word)
2080 (forward-char)
2081 (delete-region (point-marker) (search-forward "self."))
2082 (setq input (buffer-substring (point-min) (point-max)))))
2083 (python-shell-send-string-no-output
2084 (format python-eldoc-string-code input) process))))
2085 (with-current-buffer (process-buffer process)
2086 (when comint-last-prompt-overlay
2087 (delete-region comint-last-input-end
2088 (overlay-start comint-last-prompt-overlay))))
2089 (when (and help
2090 (not (string= help "\n")))
2091 help)))))
2092
2093 (defun python-eldoc-function ()
2094 "`eldoc-documentation-function' for Python.
2095 For this to work the best as possible you should call
2096 `python-shell-send-buffer' from time to time so context in
2097 inferior python process is updated properly."
2098 (python-eldoc--get-doc-at-point))
2099
2100 (defun python-eldoc-at-point (symbol)
2101 "Get help on SYMBOL using `help'.
2102 Interactively, prompt for symbol."
2103 (interactive
2104 (let ((symbol (with-syntax-table python-dotty-syntax-table
2105 (current-word)))
2106 (enable-recursive-minibuffers t))
2107 (list (read-string (if symbol
2108 (format "Describe symbol (default %s): " symbol)
2109 "Describe symbol: ")
2110 nil nil symbol))))
2111 (let ((process (python-shell-get-process)))
2112 (if (not process)
2113 (message "Eldoc needs an inferior Python process running.")
2114 (message (python-eldoc--get-doc-at-point symbol process)))))
2115
2116 \f
2117 ;;; Imenu
2118
2119 (defcustom python-imenu-include-defun-type t
2120 "Non-nil make imenu items to include its type."
2121 :type 'boolean
2122 :group 'python
2123 :safe 'booleanp)
2124
2125 (defcustom python-imenu-make-tree t
2126 "Non-nil make imenu to build a tree menu.
2127 Set to nil for speed."
2128 :type 'boolean
2129 :group 'python
2130 :safe 'booleanp)
2131
2132 (defcustom python-imenu-subtree-root-label "<Jump to %s>"
2133 "Label displayed to navigate to root from a subtree.
2134 It can contain a \"%s\" which will be replaced with the root name."
2135 :type 'string
2136 :group 'python
2137 :safe 'stringp)
2138
2139 (defvar python-imenu-index-alist nil
2140 "Calculated index tree for imenu.")
2141
2142 (defun python-imenu-tree-assoc (keylist tree)
2143 "Using KEYLIST traverse TREE."
2144 (if keylist
2145 (python-imenu-tree-assoc (cdr keylist)
2146 (ignore-errors (assoc (car keylist) tree)))
2147 tree))
2148
2149 (defun python-imenu-make-element-tree (element-list full-element plain-index)
2150 "Make a tree from plain alist of module names.
2151 ELEMENT-LIST is the defun name splitted by \".\" and FULL-ELEMENT
2152 is the same thing, the difference is that FULL-ELEMENT remains
2153 untouched in all recursive calls.
2154 Argument PLAIN-INDEX is the calculated plain index used to build the tree."
2155 (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist))
2156 (when element-list
2157 (let* ((subelement-point (cdr (assoc
2158 (mapconcat #'identity full-element ".")
2159 plain-index)))
2160 (subelement-name (car element-list))
2161 (subelement-position (python-util-position
2162 subelement-name full-element))
2163 (subelement-path (when subelement-position
2164 (butlast
2165 full-element
2166 (- (length full-element)
2167 subelement-position)))))
2168 (let ((path-ref (python-imenu-tree-assoc subelement-path
2169 python-imenu-index-alist)))
2170 (if (not path-ref)
2171 (push (cons subelement-name subelement-point)
2172 python-imenu-index-alist)
2173 (when (not (listp (cdr path-ref)))
2174 ;; Modifiy root cdr to be a list
2175 (setcdr path-ref
2176 (list (cons (format python-imenu-subtree-root-label
2177 (car path-ref))
2178 (cdr (assoc
2179 (mapconcat #'identity
2180 subelement-path ".")
2181 plain-index))))))
2182 (when (not (assoc subelement-name path-ref))
2183 (push (cons subelement-name subelement-point) (cdr path-ref))))))
2184 (python-imenu-make-element-tree (cdr element-list)
2185 full-element plain-index))))
2186
2187 (defun python-imenu-make-tree (index)
2188 "Build the imenu alist tree from plain INDEX.
2189
2190 The idea of this function is that given the alist:
2191
2192 '((\"Test\" . 100)
2193 (\"Test.__init__\" . 200)
2194 (\"Test.some_method\" . 300)
2195 (\"Test.some_method.another\" . 400)
2196 (\"Test.something_else\" . 500)
2197 (\"test\" . 600)
2198 (\"test.reprint\" . 700)
2199 (\"test.reprint\" . 800))
2200
2201 This tree gets built:
2202
2203 '((\"Test\" . ((\"jump to...\" . 100)
2204 (\"__init__\" . 200)
2205 (\"some_method\" . ((\"jump to...\" . 300)
2206 (\"another\" . 400)))
2207 (\"something_else\" . 500)))
2208 (\"test\" . ((\"jump to...\" . 600)
2209 (\"reprint\" . 700)
2210 (\"reprint\" . 800))))
2211
2212 Internally it uses `python-imenu-make-element-tree' to create all
2213 branches for each element."
2214 (setq python-imenu-index-alist nil)
2215 (mapc (lambda (element)
2216 (python-imenu-make-element-tree element element index))
2217 (mapcar (lambda (element)
2218 (split-string (car element) "\\." t)) index))
2219 python-imenu-index-alist)
2220
2221 (defun python-imenu-create-index ()
2222 "`imenu-create-index-function' for Python."
2223 (let ((index))
2224 (goto-char (point-max))
2225 (while (python-beginning-of-defun-function 1 t)
2226 (let ((defun-dotted-name
2227 (python-info-current-defun python-imenu-include-defun-type)))
2228 (push (cons defun-dotted-name (point)) index)))
2229 (if python-imenu-make-tree
2230 (python-imenu-make-tree index)
2231 index)))
2232
2233 \f
2234 ;;; Misc helpers
2235
2236 (defun python-info-current-defun (&optional include-type)
2237 "Return name of surrounding function with Python compatible dotty syntax.
2238 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2239 This function is compatible to be used as
2240 `add-log-current-defun-function' since it returns nil if point is
2241 not inside a defun."
2242 (let ((names '())
2243 (min-indent)
2244 (first-run t))
2245 (save-restriction
2246 (widen)
2247 (save-excursion
2248 (goto-char (line-end-position))
2249 (forward-comment -9999)
2250 (setq min-indent (current-indentation))
2251 (while (python-beginning-of-defun-function 1 t)
2252 (when (or (< (current-indentation) min-indent)
2253 first-run)
2254 (setq first-run nil)
2255 (setq min-indent (current-indentation))
2256 (looking-at python-nav-beginning-of-defun-regexp)
2257 (setq names (cons
2258 (if (not include-type)
2259 (match-string-no-properties 1)
2260 (mapconcat 'identity
2261 (split-string
2262 (match-string-no-properties 0)) " "))
2263 names))))))
2264 (when names
2265 (mapconcat (lambda (string) string) names "."))))
2266
2267 (defun python-info-closing-block ()
2268 "Return the point of the block the current line closes."
2269 (let ((closing-word (save-excursion
2270 (back-to-indentation)
2271 (current-word)))
2272 (indentation (current-indentation)))
2273 (when (member closing-word python-indent-dedenters)
2274 (save-excursion
2275 (forward-line -1)
2276 (while (and (> (current-indentation) indentation)
2277 (not (bobp))
2278 (not (back-to-indentation))
2279 (forward-line -1)))
2280 (back-to-indentation)
2281 (cond
2282 ((not (equal indentation (current-indentation))) nil)
2283 ((string= closing-word "elif")
2284 (when (member (current-word) '("if" "elif"))
2285 (point-marker)))
2286 ((string= closing-word "else")
2287 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2288 (point-marker)))
2289 ((string= closing-word "except")
2290 (when (member (current-word) '("try"))
2291 (point-marker)))
2292 ((string= closing-word "finally")
2293 (when (member (current-word) '("except" "else"))
2294 (point-marker))))))))
2295
2296 (defun python-info-line-ends-backslash-p ()
2297 "Return non-nil if current line ends with backslash."
2298 (string= (or (ignore-errors
2299 (buffer-substring
2300 (line-end-position)
2301 (- (line-end-position) 1))) "") "\\"))
2302
2303 (defun python-info-continuation-line-p ()
2304 "Return non-nil if current line is continuation of another."
2305 (or (python-info-line-ends-backslash-p)
2306 (string-match ",[[:space:]]*$" (buffer-substring
2307 (line-beginning-position)
2308 (line-end-position)))
2309 (save-excursion
2310 (let ((innermost-paren (progn
2311 (goto-char (line-end-position))
2312 (python-info-ppss-context 'paren))))
2313 (when (and innermost-paren
2314 (and (<= (line-beginning-position) innermost-paren)
2315 (>= (line-end-position) innermost-paren)))
2316 (goto-char innermost-paren)
2317 (looking-at (python-rx open-paren (* space) line-end)))))
2318 (save-excursion
2319 (back-to-indentation)
2320 (python-info-ppss-context 'paren))))
2321
2322 (defun python-info-block-continuation-line-p ()
2323 "Return non-nil if current line is a continuation of a block."
2324 (save-excursion
2325 (while (and (not (bobp))
2326 (python-info-continuation-line-p))
2327 (forward-line -1))
2328 (forward-line 1)
2329 (back-to-indentation)
2330 (when (looking-at (python-rx block-start))
2331 (point-marker))))
2332
2333 (defun python-info-assignment-continuation-line-p ()
2334 "Return non-nil if current line is a continuation of an assignment."
2335 (save-excursion
2336 (while (and (not (bobp))
2337 (python-info-continuation-line-p))
2338 (forward-line -1))
2339 (forward-line 1)
2340 (back-to-indentation)
2341 (when (and (not (looking-at (python-rx block-start)))
2342 (save-excursion
2343 (and (re-search-forward (python-rx not-simple-operator
2344 assignment-operator
2345 not-simple-operator)
2346 (line-end-position) t)
2347 (not (or (python-info-ppss-context 'string)
2348 (python-info-ppss-context 'paren)
2349 (python-info-ppss-context 'comment))))))
2350 (point-marker))))
2351
2352 (defun python-info-ppss-context (type &optional syntax-ppss)
2353 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2354 TYPE can be 'comment, 'string or 'parent. It returns the start
2355 character address of the specified TYPE."
2356 (let ((ppss (or syntax-ppss (syntax-ppss))))
2357 (case type
2358 ('comment
2359 (and (nth 4 ppss)
2360 (nth 8 ppss)))
2361 ('string
2362 (nth 8 ppss))
2363 ('paren
2364 (nth 1 ppss))
2365 (t nil))))
2366
2367 \f
2368 ;;; Utility functions
2369
2370 ;; Stolen from GNUS
2371 (defun python-util-merge (type list1 list2 pred)
2372 "Destructively merge lists to produce a new one.
2373 Argument TYPE is for compatibility and ignored. LIST1 and LIST2
2374 are the list to be merged. Ordering of the elements is preserved
2375 according to PRED, a `less-than' predicate on the elements."
2376 (let ((res nil))
2377 (while (and list1 list2)
2378 (if (funcall pred (car list2) (car list1))
2379 (push (pop list2) res)
2380 (push (pop list1) res)))
2381 (nconc (nreverse res) list1 list2)))
2382
2383 (defun python-util-position (item seq)
2384 "Find the first occurrence of ITEM in SEQ.
2385 Return the index of the matching item, or nil if not found."
2386 (let ((member-result (member item seq)))
2387 (when member-result
2388 (- (length seq) (length member-result)))))
2389
2390 \f
2391 ;;;###autoload
2392 (define-derived-mode python-mode fundamental-mode "Python"
2393 "Major mode for editing Python files.
2394
2395 \\{python-mode-map}
2396 Entry to this mode calls the value of `python-mode-hook'
2397 if that value is non-nil."
2398 (set (make-local-variable 'tab-width) 8)
2399 (set (make-local-variable 'indent-tabs-mode) nil)
2400
2401 (set (make-local-variable 'comment-start) "# ")
2402 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2403
2404 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2405 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2406
2407 (set (make-local-variable 'font-lock-defaults)
2408 '(python-font-lock-keywords
2409 nil nil nil nil
2410 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords)))
2411
2412 (set (make-local-variable 'indent-line-function) #'python-indent-line-function)
2413 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2414
2415 (set (make-local-variable 'paragraph-start) "\\s-*$")
2416 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function)
2417
2418 (set (make-local-variable 'beginning-of-defun-function)
2419 #'python-beginning-of-defun-function)
2420 (set (make-local-variable 'end-of-defun-function)
2421 #'python-end-of-defun-function)
2422
2423 (add-hook 'completion-at-point-functions
2424 'python-completion-complete-at-point nil 'local)
2425
2426 (setq imenu-create-index-function #'python-imenu-create-index)
2427
2428 (set (make-local-variable 'add-log-current-defun-function)
2429 #'python-info-current-defun)
2430
2431 (set (make-local-variable 'skeleton-further-elements)
2432 '((abbrev-mode nil)
2433 (< '(backward-delete-char-untabify (min python-indent-offset
2434 (current-column))))
2435 (^ '(- (1+ (current-indentation))))))
2436
2437 (set (make-local-variable 'eldoc-documentation-function)
2438 #'python-eldoc-function)
2439
2440 (add-to-list 'hs-special-modes-alist
2441 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2442 ,(lambda (arg)
2443 (python-end-of-defun-function)) nil))
2444
2445 (set (make-local-variable 'mode-require-final-newline) t)
2446
2447 (set (make-local-variable 'outline-regexp)
2448 (python-rx (* space) block-start))
2449 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2450 (set (make-local-variable 'outline-level)
2451 #'(lambda ()
2452 "`outline-level' function for Python mode."
2453 (1+ (/ (current-indentation) python-indent-offset))))
2454
2455 (python-skeleton-add-menu-items)
2456
2457 (when python-indent-guess-indent-offset
2458 (python-indent-guess-indent-offset)))
2459
2460
2461 (provide 'python)
2462 ;;; python.el ends here