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