8000 elpy/elpy.el at master · steinitzu/elpy · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
4211 lines (3731 loc) · 159 KB

elpy.el

File metadata and controls

4211 lines (3731 loc) · 159 KB
;;; elpy.el --- Emacs Python Development Environment -*- lexical-binding: t -*-
;; Copyright (C) 2012-2016 Jorgen Schaefer
;; Author: Jorgen Schaefer <contact@jorgenschaefer.de>
;; URL: https://github.com/jorgenschaefer/elpy
;; Version: 1.28.0
;; Keywords: Python, IDE, Languages, Tools
;; Package-Requires: ((company "0.9.2") (emacs "24.4") (find-file-in-project "3.3") (highlight-indentation "0.5.0") (pyvenv "1.3") (yasnippet "0.8.0") (s "1.12.0"))
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License
;; as published by the Free Software Foundation; either version 3
;; of the License, or (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; The Emacs Lisp Python Environment in Emacs
;; Elpy is an Emacs package to bring powerful Python editing to Emacs.
;; It combines a number of existing Emacs packages, both written in
;; Emacs Lisp as well as Python.
;; For more information, read the Elpy manual:
;; https://elpy.readthedocs.io/en/latest/index.html
;;; Code:
(require 'cus-edit)
(require 'etags)
(require 'files-x)
(require 'grep)
(require 'ido)
(require 'json)
(require 'python)
(require 'subr-x)
(require 'xref nil t)
(require 'cl-lib) ; for `cl-every', `cl-copy-list', `cl-delete-if-not'
(require 'elpy-refactor)
(require 'elpy-django)
(require 'elpy-profile)
(require 'elpy-shell)
(require 'pyvenv)
(require 'find-file-in-project)
(defconst elpy-version "1.28.0"
"The version of the Elpy lisp code.")
;;;;;;;;;;;;;;;;;;;;;;
;;; User customization
(defgroup elpy nil
"The Emacs Lisp Python Environment."
:prefix "elpy-"
:group 'languages)
(defcustom elpy-mode-hook nil
"Hook run when `elpy-mode' is enabled.
This can be used to enable minor modes for Python development."
:type 'hook
:options '(subword-mode hl-line-mode)
:group 'elpy)
(defcustom elpy-modules '(elpy-module-sane-defaults
elpy-module-company
elpy-module-eldoc
elpy-module-flymake
elpy-module-highlight-indentation
elpy-module-pyvenv
elpy-module-yasnippet
elpy-module-django)
"Which Elpy modules to use.
Elpy can use a number of modules for additional features, which
can be inidividually enabled or disabled."
:type '(set (const :tag "Inline code completion (company-mode)"
elpy-module-company)
(const :tag "Show function signatures (ElDoc)"
elpy-module-eldoc)
(const :tag "Highlight syntax errors (Flymake)"
elpy-module-flymake)
(const :tag "Show the virtualenv in the mode line (pyvenv)"
elpy-module-pyvenv)
(const :tag "Display indentation markers (highlight-indentation)"
elpy-module-highlight-indentation)
(const :tag "Expand code snippets (YASnippet)"
elpy-module-yasnippet)
(const :tag "Django configurations (Elpy-Django)"
elpy-module-django)
(const :tag "Automatically update documentation (Autodoc)."
elpy-module-autodoc)
(const :tag "Configure some sane defaults for Emacs"
elpy-module-sane-defaults))
:group 'elpy)
(defcustom elpy-project-ignored-directories
'(".tox" "build" "dist" ".cask" ".ipynb_checkpoints")
"Directories ignored by functions working on the whole project.
This is in addition to `vc-directory-exclusion-list'
and `grep-find-ignored-directories', as appropriate."
:type '(repeat string)
:safe (lambda (val)
(cl-every #'stringp val))
:group 'elpy)
(defun elpy-project-ignored-directories ()
"Compute the list of ignored directories for project.
Combines
`elpy-project-ignored-directories'
`vc-directory-exclusion-list'
`grep-find-ignored-directories'"
(delete-dups
(append elpy-project-ignored-directories
vc-directory-exclusion-list
(if (fboundp 'rgrep-find-ignored-directories)
(rgrep-find-ignored-directories (elpy-project-root))
(cl-delete-if-not #'stringp (cl-copy-list
grep-find-ignored-directories))))))
(defcustom elpy-project-root nil
"The root of the project the current buffer is in.
There is normally no use in setting this variable directly, as
Elpy tries to detect the project root automatically. See
`elpy-project-root-finder-functions' for a way of influencing
this.
Setting this variable globally will override Elpy's automatic
project detection facilities entirely.
Alternatively, you can set this in file- or directory-local
variables using \\[add-file-local-variable] or
\\[add-dir-local-variable].
Do not use this variable in Emacs Lisp programs. Instead, call
the `elpy-project-root' function. It will do the right thing."
:type 'directory
:safe 'file-directory-p
:group 'elpy)
(make-variable-buffer-local 'elpy-project-root)
(defcustom elpy-project-root-finder-functions
'(elpy-project-find-projectile-root
elpy-project-find-python-root
elpy-project-find-git-root
elpy-project-find-hg-root
elpy-project-find-svn-root)
"List of functions to ask for the current project root.
These will be checked in turn. The first directory found is used."
:type '(set (const :tag "Projectile project root"
elpy-project-find-projectile-root)
(const :tag "Python project (setup.py, setup.cfg)"
elpy-project-find-python-root)
(const :tag "Git repository root (.git)"
elpy-project-find-git-root)
(const :tag "Mercurial project root (.hg)"
elpy-project-find-hg-root)
(const :tag "Subversion project root (.svn)"
elpy-project-find-svn-root))
:group 'elpy)
(make-obsolete-variable 'elpy-company-hide-modeline
'elpy-remove-modeline-lighter
"1.10.0")
(defcustom elpy-remove-modeline-lighter t
"Non-nil if Elpy should remove most mode line display.
Modeline shows many minor modes currently active. For Elpy, this is mostly
uninteresting information, but if you rely on your modeline in other modes,
you might want to keep it."
:type 'boolean
:group 'elpy)
(defcustom elpy-rpc-maximum-buffer-age (* 5 60)
"Seconds after which Elpy automatically closes an unused RPC buffer.
Elpy creates RPC buffers over time, depending on python interpreters
and the project root. When there are many projects being worked on,
these can accumulate. Setting this variable to an integer will close
buffers and processes when they have not been used for this amount of
seconds.
Setting this variable to nil will disable the behavior."
:type '(choice (const :tag "Never" nil)
integer)
:group 'elpy)
(defcustom elpy-rpc-large-buffer-size 4096
"Size for a source buffer up to which it will be sent directly.
The Elpy RPC protocol uses JSON as the serialization format.
Large buffers take a long time to encode, so Elpy can transmit
them via temporary files. If a buffer is larger than this value,
it is sent via a temporary file."
:type 'integer
:safe #'integerp
:group 'elpy)
(defcustom elpy-rpc-ignored-buffer-size 102400
"Size for a source buffer over which Elpy completion will not work.
To provide completion, Elpy's backends have to parse the whole
file every time. For very large files, this is slow, and can make
Emacs laggy. Elpy will simply not work on buffers larger than
this to prevent this from happening."
:type 'integer
:safe #'integerp
:group 'elpy)
(defcustom elpy-rpc-python-command (if (equal system-type 'windows-nt)
(or (executable-find "py")
(executable-find "pythonw")
"python")
"python")
"The Python interpreter for the RPC backend.
This should be the same interpreter the project will be run with,
and not an interactive shell like ipython."
:type '(choice (const :tag "python" "python")
(const :tag "python2" "python2")
(const :tag "python3" "python3")
(const :tag "pythonw (Python on Windows)" "pythonw")
(const :tag "py (other Python on Windows)" "py")
(string :tag "Other"))
:safe (lambda (val)
(member val '("python" "python2" "python3" "pythonw")))
:group 'elpy)
(defcustom elpy-rpc-pythonpath (file-name-directory (locate-library "elpy"))
"A directory to add to the PYTHONPATH for the RPC process.
This should be a directory where the elpy module can be found. If
this is nil, it's assumed elpy can be found in the standard path.
Usually, there is no need to change this."
:type 'directory
:safe #'file-directory-p
:group 'elpy)
(defcustom elpy-rpc-timeout 1
"Number of seconds to wait for a response when blocking.
When Elpy blocks Emacs to wait for a response from the RPC
process, it will assume it won't come or wait too long after this
many seconds. On a slow computer, or if you have a large project,
you might want to increase this.
A setting of nil means to block indefinitely."
:type '(choice (const :tag "Block indefinitely" nil)
integer)
:safe (lambda (val)
(or (integerp val)
(null val)))
:group 'elpy)
(defcustom elpy-rpc-error-timeout 30
"Minimum number of seconds between error popups.
When Elpy encounters an error in the backend, it will display a
lengthy description of the problem for a bug report. This hangs
Emacs for a moment, and can be rather annoying if it happens
repeatedly while editing a source file.
If this variabl is non-nil, Elpy will not display the error
message again within this amount of seconds."
:type 'integer
:group 'elpy)
(defcustom elpy-company-post-completion-function 'ignore
"Your preferred Company post completion function.
Elpy can automatically insert parentheses after completing
callable objects.
The heuristic on when to insert these parentheses can easily be
wrong, though, so this is disabled by default. Set this variable
to the function `elpy-company-post-complete-parens' to enable
this feature."
:type '(choice (const :tag "Ignore post complete" ignore)
(const :tag "Complete callables with parens"
elpy-company-post-complete-parens)
(function :tag "Other function"))
:group 'elpy)
(defcustom elpy-get-info-from-shell nil
"If t, use the shell to gather docstrings and completions.
Normally elpy provides completion and documentation using static code analysis (from jedi). With this option set to t, elpy will add the completion candidates and the docstrings from the associated python shell. This allows to have decent completion candidates and documentation when the static code analysis fails."
:type 'boolean
:group 'elpy)
(defcustom elpy-get-info-from-shell-timeout 1
"Timeout (in seconds) for gathering information from the shell."
:type 'number
:group 'elpy)
(defcustom elpy-eldoc-show-current-function t
"If true, show the current function if no calltip is available.
When Elpy can not find the calltip of the function call at point,
it can show the name of the function or class and method being
edited instead. Setting this variable to nil disables this feature."
:type 'boolean
:group 'elpy)
(defcustom elpy-test-runner 'elpy-test-discover-runner
"The test runner to use to run tests."
:type '(choice (const :tag "Unittest Discover" elpy-test-discover-runner)
(const :tag "Green" elpy-test-green-runner)
(const :tag "Django Discover" elpy-test-django-runner)
(const :tag "Nose" elpy-test-nose-runner)
(const :tag "py.test" elpy-test-pytest-runner)
(const :tag "Twisted Trial" elpy-test-trial-runner))
:safe 'elpy-test-runner-p
:group 'elpy)
(defcustom elpy-test-discover-runner-command '("python" "-m" "unittest")
"The command to use for `elpy-test-discover-runner'."
:type '(repeat string)
:group 'elpy)
(defcustom elpy-test-green-runner-command '("green")
"The command to use for `elpy-test-green-runner'."
:type '(repeat string)
:group 'elpy)
(defcustom elpy-test-nose-runner-command '("nosetests")
"The command to use for `elpy-test-nose-runner'."
:type '(repeat string)
:group 'elpy)
(defcustom elpy-test-trial-runner-command '("trial")
"The command to use for `elpy-test-trial-runner'."
:type '(repeat string)
:group 'elpy)
(defcustom elpy-test-pytest-runner-command '("py.test")
"The command to use for `elpy-test-pytest-runner'."
:type '(repeat string)
:group 'elpy)
(defcustom elpy-test-compilation-function 'compile
"Function used by `elpy-test-run' to run a test command.
The function should behave similarly to `compile'. Another good
option is `pdb'."
:type 'string
:group 'elpy)
(defcustom elpy-rgrep-file-pattern "*.py"
"FILES to use for `elpy-rgrep-symbol'."
:type 'string
:group 'elpy)
(defcustom elpy-disable-backend-error-display t
"Non-nil if Elpy should disable backend error display."
:type 'boolean
:group 'elpy)
(defcustom elpy-syntax-check-command "flake8"
"The command to use for `elpy-check'."
:type 'string
:group 'elpy)
;;;;;;;;;;;;;
;;; Elpy Mode
(defvar elpy-refactor-map
(let ((map (make-sparse-keymap "Refactor")))
(define-key map (kbd "i") (cons (format "%smport fixup"
(propertize "i" 'face 'bold))
'elpy-importmagic-fixup))
(define-key map (kbd "f") (cons (format "%sormat code"
(propertize "f" 'face 'bold))
'elpy-format-code))
(define-key map (kbd "r") (cons (format "%sefactor"
(propertize "r" 'face 'bold))
'elpy-refactor))
map)
"Key map for the refactor command")
(defvar elpy-mode-map
(let ((map (make-sparse-keymap)))
;; Alphabetical order to make it easier to find free C-c C-X
;; bindings in the future. Heh.
;; (define-key map (kbd "<backspace>") 'python-indent-dedent-line-backspace)
;; (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
;; (define-key map (kbd "C-M-x") 'python-shell-send-defun)
;; (define-key map (kbd "C-c <") 'python-indent-shift-left)
;; (define-key map (kbd "C-c >") 'python-indent-shift-right)
(define-key map (kbd "C-c RET") 'elpy-importmagic-add-import)
(define-key map (kbd "C-c C-b") 'elpy-nav-expand-to-indentation)
(define-key map (kbd "C-c C-c") 'elpy-shell-send-region-or-buffer)
(define-key map (kbd "C-c C-d") 'elpy-doc)
(define-key map (kbd "C-c C-e") 'elpy-multiedit-python-symbol-at-point)
(define-key map (kbd "C-c C-f") 'elpy-find-file)
(define-key map (kbd "C-c C-n") 'elpy-flymake-next-error)
(define-key map (kbd "C-c C-o") 'elpy-occur-definitions)
(define-key map (kbd "C-c C-p") 'elpy-flymake-previous-error)
(define-key map (kbd "C-c C-s") 'elpy-rgrep-symbol)
(define-key map (kbd "C-c C-t") 'elpy-test)
(define-key map (kbd "C-c C-v") 'elpy-check)
(define-key map (kbd "C-c C-z") 'elpy-shell-switch-to-shell)
(define-key map (kbd "C-c C-k") 'elpy-shell-kill)
(define-key map (kbd "C-c C-K") 'elpy-shell-kill-all)
(define-key map (kbd "C-c C-r") elpy-refactor-map)
(define-key map (kbd "C-c C-x") elpy-django-mode-map)
(define-key map (kbd "<S-return>") 'elpy-open-and-indent-line-below)
(define-key map (kbd "<C-S-return>") 'elpy-open-and-indent-line-above)
(define-key map (kbd "<C-return>") 'elpy-shell-send-statement-and-step)
(define-key map (kbd "<C-down>") 'elpy-nav-forward-block)
(define-key map (kbd "<C-up>") 'elpy-nav-backward-block)
(define-key map (kbd "<C-left>") 'elpy-nav-backward-indent)
(define-key map (kbd "<C-right>") 'elpy-nav-forward-indent)
(define-key map (kbd "<M-down>") 'elpy-nav-move-line-or-region-down)
(define-key map (kbd "<M-up>") 'elpy-nav-move-line-or-region-up)
(define-key map (kbd "<M-left>") 'elpy-nav-indent-shift-left)
(define-key map (kbd "<M-right>") 'elpy-nav-indent-shift-right)
(if (not (fboundp 'xref-find-definitions))
(define-key map (kbd "M-.") 'elpy-goto-definition))
(if (not (fboundp 'xref-find-definitions-other-window))
(define-key map (kbd "C-x 4 M-.") 'elpy-goto-definition-other-window)
(define-key map (kbd "C-x 4 M-.") 'xref-find-definitions-other-window))
(if (fboundp 'xref-pop-marker-stack)
(define-key map (kbd "M-*") 'xref-pop-marker-stack))
(define-key map (kbd "M-TAB") 'elpy-company-backend)
map)
"Key map for the Emacs Lisp Python Environment.")
(defvar elpy-shell-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "e") 'elpy-shell-send-statement)
(define-key map (kbd "E") 'elpy-shell-send-statement-and-go)
(define-key map (kbd "s") 'elpy-shell-send-top-statement)
(define-key map (kbd "S") 'elpy-shell-send-top-statement-and-go)
(define-key map (kbd "f") 'elpy-shell-send-defun)
(define-key map (kbd "F") 'elpy-shell-send-defun-and-go)
(define-key map (kbd "c") 'elpy-shell-send-defclass)
(define-key map (kbd "C") 'elpy-shell-send-defclass-and-go)
(define-key map (kbd "o") 'elpy-shell-send-group)
(define-key map (kbd "O") 'elpy-shell-send-group-and-go)
(define-key map (kbd "w") 'elpy-shell-send-codecell)
(define-key map (kbd "W") 'elpy-shell-send-codecell-and-go)
(define-key map (kbd "r") 'elpy-shell-send-region-or-buffer)
(define-key map (kbd "R") 'elpy-shell-send-region-or-buffer-and-go)
(define-key map (kbd "b") 'elpy-shell-send-buffer)
(define-key map (kbd "B") 'elpy-shell-send-buffer-and-go)
(define-key map (kbd "C-e") 'elpy-shell-send-statement-and-step)
(define-key map (kbd "C-S-E") 'elpy-shell-send-statement-and-step-and-go)
(define-key map (kbd "C-s") 'elpy-shell-send-top-statement-and-step)
(define-key map (kbd "C-S-S") 'elpy-shell-send-top-statement-and-step-and-go)
(define-key map (kbd "C-f") 'elpy-shell-send-defun-and-step)
(define-key map (kbd "C-S-F") 'elpy-shell-send-defun-and-step-and-go)
(define-key map (kbd "C-c") 'elpy-shell-send-defclass-and-step)
(define-key map (kbd "C-S-C") 'elpy-shell-send-defclass-and-step-and-go)
(define-key map (kbd "C-o") 'elpy-shell-s 10BC8 end-group-and-step)
(define-key map (kbd "C-S-O") 'elpy-shell-send-group-and-step-and-go)
(define-key map (kbd "C-w") 'elpy-shell-send-codecell-and-step)
(define-key map (kbd "C-S-W") 'elpy-shell-send-codecell-and-step-and-go)
(define-key map (kbd "C-r") 'elpy-shell-send-region-or-buffer-and-step)
(define-key map (kbd "C-S-R") 'elpy-shell-send-region-or-buffer-and-step-and-go)
(define-key map (kbd "C-b") 'elpy-shell-send-buffer-and-step)
(define-key map (kbd "C-S-B") 'elpy-shell-send-buffer-and-step-and-go)
map)
"Key map for the shell related commands")
(fset 'elpy-shell-map elpy-shell-map)
(defcustom elpy-shell-command-prefix-key "C-c C-y"
"Prefix key used to call elpy shell related commands.
This option need to bet set through `customize' or `customize-set-variable' to be taken into account."
:type 'string
:group 'elpy
:set
(lambda (var key)
(when (and (boundp var) (symbol-value var))
(define-key elpy-mode-map (kbd (symbol-value var)) nil))
(when key
(define-key elpy-mode-map (kbd key) 'elpy-shell-map)
(set var key))))
(defvar elpy-pdb-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "g") 'elpy-pdb-debug-buffer)
(define-key map (kbd "p") 'elpy-pdb-break-at-point)
(define-key map (kbd "e") 'elpy-pdb-debug-last-exception)
(define-key map (kbd "b") 'elpy-pdb-toggle-breakpoint-at-point)
map)
"Key map for the shell related commands")
(fset 'elpy-pdb-map elpy-pdb-map)
(define-key elpy-mode-map (kbd "C-c C-g") 'elpy-pdb-map)
(easy-menu-define elpy-menu elpy-mode-map
"Elpy Mode Menu"
'("Elpy"
["Documentation" elpy-doc
:help "Get documentation for symbol at point"]
["Run Tests" elpy-test
:help "Run test at point, or all tests in the project"]
["Go to Definition" elpy-goto-definition
:help "Go to the definition of the symbol at point"]
["Go to previous definition" pop-tag-mark
:active (not (ring-empty-p find-tag-marker-ring))
:help "Return to the position"]
["Complete" elpy-company-backend
:keys "M-TAB"
:help "Complete at point"]
["Refactor" elpy-refactor
:help "Refactor options"]
"---"
("Interactive Python"
["Switch to Python Shell" elpy-shell-switch-to-shell
:help "Start and switch to the interactive Python"]
["Send Region or Buffer" elpy-shell-send-region-or-buffer
:label (if (use-region-p)
"Send Region to Python"
"Send Buffer to Python")
:help "Send the current region or the whole buffer to Python"]
["Send Definition" python-shell-send-defun
:help "Send current definition to Python"]
["Kill Python shell" elpy-shell-kill
:help "Kill the current Python shell"]
["Kill all Python shells" elpy-shell-kill-all
:help "Kill all Python shells"])
("Debugging"
["Debug buffer" elpy-pdb-debug-buffer
:help "Debug the current buffer using pdb"]
["Debug at point" elpy-pdb-break-at-point
:help "Debug the current buffer and stop at the current position"]
["Debug last exception" elpy-pdb-debug-last-exception
:help "Run post-mortem pdb on the last exception"]
["Add/remove breakpoint" elpy-pdb-toggle-breakpoint-at-point
:help "Add or remove a breakpoint at the current position"])
("Project"
["Find File" elpy-find-file
:help "Interactively find a file in the current project"]
["Find Symbol" elpy-rgrep-symbol
:help "Find occurrences of a symbol in the current project"]
["Set Project Root" elpy-set-project-root
:help "Change the current project root"]
["Set Project Variable" elpy-set-project-variable
:help "Configure a project-specific option"])
("Syntax Check"
["Check Syntax" elpy-check
:help "Check the syntax of the current file"]
["Next Error" elpy-flymake-next-error
:help "Go to the next inline error, if any"]
["Previous Error" elpy-flymake-previous-error
:help "Go to the previous inline error, if any"])
("Indentation Blocks"
["Dedent" python-indent-shift-left
:help "Dedent current block or region"
:suffix (if (use-region-p) "Region" "Block")]
["Indent" python-indent-shift-right
:help "Indent current block or region"
:suffix (if (use-region-p) "Region" "Block")]
["Up" elpy-nav-move-line-or-region-up
:help "Move current block or region up"
:suffix (if (use-region-p) "Region" "Block")]
["Down" elpy-nav-move-line-or-region-down
:help "Move current block or region down"
:suffix (if (use-region-p) "Region" "Block")])
"---"
["Configure" elpy-config t]))
;;;###autoload
(defun elpy-enable (&optional ignored)
"Enable Elpy in all future Python buffers."
(interactive)
(when (< emacs-major-version 24)
(error "Elpy requires Emacs 24 or newer"))
(when ignored
(warn "The argument to `elpy-enable' is deprecated, customize `elpy-modules' instead"))
(let ((filename (find-lisp-object-file-name 'python-mode
'symbol-function)))
(when (and filename
(string-match "/python-mode\\.el\\'"
filename))
(error (concat "You are using python-mode.el. "
"Elpy only works with python.el from "
"Emacs 24 and above"))))
(elpy-modules-global-init)
(define-key inferior-python-mode-map (kbd "C-c C-z") 'elpy-shell-switch-to-buffer)
(add-hook 'python-mode-hook 'elpy-mode)
(add-hook 'pyvenv-post-activate-hooks 'elpy-rpc--disconnect)
(add-hook 'inferior-python-mode-hook 'elpy-shell--enable-output-filter))
(defun elpy-disable ()
"Disable Elpy in all future Python buffers."
(interactive)
(remove-hook 'python-mode-hook 'elpy-mode)
(remove-hook 'inferior-python-mode-hook 'elpy-shell--enable-output-filter)
(elpy-modules-global-stop))
;;;###autoload
(define-minor-mode elpy-mode
"Minor mode in Python buffers for the Emacs Lisp Python Environment.
This mode fully supports virtualenvs. Once you switch a
virtualenv using \\[pyvenv-workon], you can use
\\[elpy-rpc-restart] to make the elpy Python process use your
virtualenv.
\\{elpy-mode-map}"
:lighter " Elpy"
(when (not (derived-mode-p 'python-mode))
(error "Elpy only works with `python-mode'"))
(when (boundp 'xref-backend-functions)
(add-hook 'xref-backend-functions #'elpy--xref-backend nil t))
(cond
(elpy-mode
(elpy-modules-buffer-init))
((not elpy-mode)
(elpy-modules-buffer-stop))))
;;;;;;;;;;;;;
;;; Elpy News
(defun elpy-news ()
"Display Elpy's release notes."
(interactive)
(message "The Elpy News command is deprecated and will be removed in future versions of Elpy"))
;;;;;;;;;;;;;;;
;;; Elpy Config
(defvar elpy-config--related-custom-groups
'(("Elpy" elpy "elpy-")
("Python" python "python-")
("Virtual Environments (Pyvenv)" pyvenv "pyvenv-")
("Completion (Company)" company "company-")
("Call Signatures (ElDoc)" eldoc "eldoc-")
("Inline Errors (Flymake)" flymake "flymake-")
("Snippets (YASnippet)" yasnippet "yas-")
("Directory Grep (rgrep)" grep "grep-")
("Search as You Type (ido)" ido "ido-")
("Django extension" elpy-django "elpy-django-")
("Autodoc extension" elpy-autodoc "elpy-autodoc-")
;; ffip does not use defcustom
;; highlight-indent does not use defcustom, either. Its sole face
;; is defined in basic-faces.
))
(defvar elpy-config--get-config "import json
import sys
import warnings
warnings.filterwarnings('ignore', category=FutureWarning)
try:
import xmlrpclib
except ImportError:
import xmlrpc.client as xmlrpclib
from distutils.version import LooseVersion
def latest(package, version=None):
try:
with xmlrpclib.ServerProxy('https://pypi.python.org/pypi') as pypi:
latest = pypi.package_releases(package)[0]
if version is None or LooseVersion(version) < LooseVersion(latest):
return latest
else:
return None
except:
return None
config = {}
config['python_version'] = ('{major}.{minor}.{micro}'
.format(major=sys.version_info[0],
minor=sys.version_info[1],
micro=sys.version_info[2]))
try:
import elpy
config['elpy_version'] = elpy.__version__
except:
config['elpy_version'] = None
try:
import jedi
if isinstance(jedi.__version__, tuple):
config['jedi_version'] = '.'.join(str(x) for x in jedi.__version__)
else:
config['jedi_version'] = jedi.__version__
config['jedi_latest'] = latest('jedi', config['jedi_version'])
except:
config['jedi_version'] = None
config['jedi_latest'] = latest('jedi')
try:
import rope
config['rope_version'] = rope.VERSION
if sys.version_info[0] <= 2:
config['rope_latest'] = latest('rope', config['rope_version'])
else:
config['rope_latest'] = latest('rope_py3k', config['rope_version'])
except:
config['rope_version'] = None
config['rope_latest'] = latest('rope')
try:
import autopep8
config['autopep8_version'] = autopep8.__version__
config['autopep8_latest'] = latest('autopep8', config['autopep8_version'])
except:
config['autopep8_version'] = None
config['autopep8_latest'] = latest('autopep8')
try:
import yapf
config['yapf_v 8 ersion&# 10BC8 039;] = yapf.__version__
config['yapf_latest'] = latest('yapf', config['yapf_version'])
except:
config['yapf_version'] = None
config['yapf_latest'] = latest('yapf')
try:
import black
config['black_version'] = black.__version__
config['black_latest'] = latest('black', config['black_version'])
except:
config['black_version'] = None
config['black_latest'] = latest('black')
json.dump(config, sys.stdout)
")
(defun elpy-config-error (&optional fmt &rest args)
"Note a configuration problem.
This will show a message in the minibuffer that tells the user to
use \\[elpy-config]."
(let ((msg (if fmt
(apply #'format fmt args)
"Elpy is not properly configured")))
(error "%s; use M-x elpy-config to configure it" msg)))
;;;###autoload
(defun elpy-config ()
"Configure Elpy.
This function will pop up a configuration buffer, which is mostly
a customize buffer, but has some more options."
(interactive)
(let ((buf (custom-get-fresh-buffer "*Elpy Config*"))
(config (elpy-config--get-config))
(custom-search-field nil))
(with-current-buffer buf
(elpy-insert--header "Elpy Configuration")
(elpy-config--insert-configuration-problems config)
(elpy-insert--header "Options")
(let ((custom-buffer-style 'tree))
(Custom-mode)
(elpy-config--insert-help)
(dolist (cust elpy-config--related-custom-groups)
(widget-create 'custom-group
:custom-last t
:custom-state 'hidden
:tag (car cust)
:value (cadr cust)))
(widget-setup)
(goto-char (point-min))))
(pop-to-buffer-same-window buf)))
;;;###autoload
(defun elpy-version ()
"Display the version of Elpy."
(interactive)
(message "Elpy %s (use M-x elpy-config for details)" elpy-version))
(defun elpy-config--insert-help ()
(let ((start (point)))
;; Help display from `customize-browse'
(widget-insert (format "\
%s buttons; type RET or click mouse-1
on a button to invoke its action.
Invoke [+] to expand a group, and [-] to collapse an expanded group.\n"
(if custom-raised-buttons
"`Raised' text indicates"
"Square brackets indicate")))
(if custom-browse-only-groups
(widget-insert "\
Invoke the [Group] button below to edit that item in another window.\n\n")
(widget-insert "Invoke the ")
(widget-create 'item
:format "%t"
:tag "[Group]"
:tag-glyph "folder")
(widget-insert ", ")
(widget-create 'item
:format "%t"
:tag "[Face]"
:tag-glyph "face")
(widget-insert ", and ")
(widget-create 'item
:format "%t"
:tag "[Option]"
:tag-glyph "option")
(widget-insert " buttons below to edit that
item in another window.\n\n")
(fill-region start (point)))))
(defun elpy-config--insert-configuration-problems (&optional config)
"Insert help text and widgets for configuration problems."
(when (not config)
(setq config (elpy-config--get-config)))
(let* ((python-version (gethash "python_version" config))
(rope-pypi-package (if (and python-version
(string-match "^3\\." python-version))
"rope_py3k"
"rope")))
(elpy-config--insert-configuration-table config)
(insert "\n")
;; Python not found
(when (not (gethash "python_rpc_executable" config))
(elpy-insert--para
"Elpy can not find the configured Python interpreter. Please make "
"sure that the variable `elpy-rpc-python-command' points to a "
"command in your PATH. You can change the variable below.\n\n"))
;; No virtual env
(when (and (gethash "python_rpc_executable" config)
(not (gethash "virtual_env" config)))
(elpy-insert--para
"You have not activated a virtual env. While Elpy supports this, "
"it is often a good idea to work inside a virtual env. You can use "
"M-x pyvenv-activate or M-x pyvenv-workon to activate a virtual "
"env.\n\n"))
;; No virtual env, but ~/.local/bin not in PATH
(when (and (not (memq system-type '(ms-dos windows-nt)))
(gethash "python_rpc_executable" config)
(not pyvenv-virtual-env)
(not (or (member (expand-file-name "~/.local/bin")
exec-path)
(member (expand-file-name "~/.local/bin/")
exec-path))))
(elpy-insert--para
"The directory ~/.local/bin/ is not in your PATH. As there is "
"no active virtualenv, installing Python packages locally will "
"place executables in that directory, so Emacs won't find them. "
"If you are missing some commands, do add this directory to your "
"PATH -- and then do `elpy-rpc-restart'.\n\n"))
;; Python found, but can't find the elpy module
(when (and (gethash "python_rpc_executable" config)
(not (gethash "elpy_version" config)))
(elpy-insert--para
"The Python interpreter could not find the elpy module. "
"Make sure the module is installed"
(if (gethash "virtual_env" config)
" in the current virtualenv.\n"
".\n"))
(insert "\n")
(widget-create 'elpy-insert--pip-button :package "elpy")
(insert "\n\n"))
;; Bad backend version
(when (and (gethash "elpy_version" config)
(not (equal (gethash "elpy_version" config)
elpy-version)))
(let ((elpy-python-version (gethash "elpy_version" config)))
(elpy-insert--para
"The Elpy backend is version " elpy-python-version " while "
"the Emacs package is " elpy-version ". This is incompatible. "
(if (version< elpy-python-version elpy-version)
"Please upgrade the Python module."
"Please upgrade the Emacs Lisp package.")
"\n")))
;; Otherwise unparseable output.
(when (gethash "error_output" config)
(elpy-insert--para
"There was an unexpected problem starting the RPC process. Please "
"check the following output to see if this makes sense to you. "
"To me, it doesn't.\n")
(insert "\n"
(gethash "error_output" config) "\n"
"\n"))
;; Interactive python interpreter not in the current virtual env
(when (and pyvenv-virtual-env
(not (string-prefix-p (expand-file-name pyvenv-virtual-env)
(executable-find
python-shell-interpreter))))
(elpy-insert--para
"The python interactive interpreter (" python-shell-interpreter
") is not installed on the current virtualenv ("
pyvenv-virtual-env "). The system binary ("
(executable-find python-shell-interpreter)
") will be used instead."
"\n")
(insert "\n")
(widget-create 'elpy-insert--pip-button
:package python-shell-interpreter)
(insert "\n\n"))
;; Requested backend unavailable
(when (and (gethash "python_rpc_executable" config)
(not (gethash "jedi_version" config)))
(elpy-insert--para
"The jedi package is not available. Completion and code navigation will"
" not work.\n")
(insert "\n")
(widget-create 'elpy-insert--pip-button
:package "jedi")
(insert "\n\n"))
;; Newer version of Rope available
(when (and (gethash "rope_version" config)
(gethash "rope_latest" config))
(elpy-insert--para
"There is a newer version of Rope available.\n")
(insert "\n")
(widget-create 'elpy-insert--pip-button
:package rope-pypi-package :upgrade t)
(insert "\n\n"))
;; Newer version of Jedi available
(when (and (gethash "jedi_version" config)
(gethash "jedi_latest" config))
(elpy-insert--para
"There is a newer version of Jedi available.\n")
(insert "\n")
(widget-create 'elpy-insert--pip-button
:package "jedi" :upgrade t)
(insert "\n\n"))
;; No autopep8 available
(when (not (gethash "autopep8_version" config))
(elpy-insert--para
"The autopep8 package is not available. Commands using this will "
"not work.\n")
(insert "\n")
(widget-create 'elpy-insert--pip-button
:package "autopep8")
(insert "\n\n"))
;; Newer version of autopep8 available
(when (and (gethash "autopep8_version" config)
(gethash "autopep8_latest" config))
(elpy-insert--para
"There is a newer version of the autopep8 package available.\n")
(insert "\n")
(widget-create 'elpy-insert--pip-button
:package "autopep8" :upgrade t)
(insert "\n\n"))
;; No yapf available
(when (not (gethash "yapf_version" config))
(elpy-insert--para
"The yapf package is not available. Commands using this will "
"not work.\n")
(insert "\n")
(widget-create 'elpy-insert--pip-button
:package "yapf")
(insert "\n\n"))
;; Newer version of yapf available
(when (and (gethash "yapf_version" config)
(gethash "yapf_latest" config))
(elpy-insert--para
"There is a newer version of the yapf package available.\n")
(insert "\n")
(widget-create 'elpy-insert--pip-button
:package "yapf" :upgrade t)
(insert "\n\n"))
;; No black available
(when (not (gethash "black_version" config))
(elpy-insert--para
0