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