[英]How can I make emacs-jedi use project-specific virtualenvs
我想emacs-jedi检测我在不同项目中编辑文件的时间,并使用相应的virtualenv(如果可用)。 按照惯例,我的virtualenvs与我的项目同名。 它们位于$HOME/.virtualenvs/
我找到了kenobi.el,但它假设在项目根目录的bin目录中找到了virtualenvs。 它还有一些我根本不需要的其他功能。
在kenobi.el的启发下,我为jedi编写了以下初始化。 它工作得很好,但并不完美。
如果我从项目中导入库A
,则A
导入B
我能够跳到A
定义的定义,但是一旦出现,我就无法继续跳到B
定义。
我的初始化:
(defun project-directory (buffer-name)
(let ((git-dir (file-name-directory buffer-name)))
(while (and (not (file-exists-p (concat git-dir ".git")))
git-dir)
(setq git-dir
(if (equal git-dir "/")
nil
(file-name-directory (directory-file-name git-dir)))))
git-dir))
(defun project-name (buffer-name)
(let ((git-dir (project-directory buffer-name)))
(if git-dir
(file-name-nondirectory
(directory-file-name git-dir))
nil)))
(defun virtualenv-directory (buffer-name)
(let ((venv-dir (expand-file-name
(concat "~/.virtualenvs/" (project-name buffer-name)))))
(if (and venv-dir (file-exists-p venv-dir))
venv-dir
nil)))
(defun jedi-setup-args ()
(let ((venv-dir (virtualenv-directory buffer-file-name)))
(when venv-dir
(set (make-local-variable 'jedi:server-args) (list "--virtual-env" venv-dir)))))
(setq jedi:setup-keys t)
(setq jedi:complete-on-dot t)
(add-hook 'python-mode-hook 'jedi-setup-args)
(add-hook 'python-mode-hook 'jedi:setup)
我如何初始化jedi有什么问题?
我现在已经确定了一个使用virtualenvwrapper ELPA包来激活virtualenvs的解决方案,允许emacs-jedi从VIRTUAL_ENV环境变量中获取virtualenv路径。
这是一个完整的,有效的emacs-jedi初始化:
(defun project-directory (buffer-name)
"Return the root directory of the project that contain the
given BUFFER-NAME. Any directory with a .git or .jedi file/directory
is considered to be a project root."
(interactive)
(let ((root-dir (file-name-directory buffer-name)))
(while (and root-dir
(not (file-exists-p (concat root-dir ".git")))
(not (file-exists-p (concat root-dir ".jedi"))))
(setq root-dir
(if (equal root-dir "/")
nil
(file-name-directory (directory-file-name root-dir)))))
root-dir))
(defun project-name (buffer-name)
"Return the name of the project that contain the given BUFFER-NAME."
(let ((root-dir (project-directory buffer-name)))
(if root-dir
(file-name-nondirectory
(directory-file-name root-dir))
nil)))
(defun jedi-setup-venv ()
"Activates the virtualenv of the current buffer."
(let ((project-name (project-name buffer-file-name)))
(when project-name (venv-workon project-name))))
(setq jedi:setup-keys t)
(setq jedi:complete-on-dot t)
(add-hook 'python-mode-hook 'jedi-setup-venv)
(add-hook 'python-mode-hook 'jedi:setup)
请记住,您必须先安装virtualenvwrapper。
阅读virtualenvwrapper文档 ,了解自动激活项目虚拟环境的另一种方法。 简而言之,您可以在项目的根目录中创建.dir-locals.el
文件,其中包含以下内容:
((python-mode . ((project-venv-name . "myproject-env"))))
将"myproject-env"
更改为virtualenv的名称,并使用python-mode
钩子激活virtualenvironment:
(add-hook 'python-mode-hook (lambda ()
(hack-local-variables)
(venv-workon project-venv-name)))
(add-hook 'python-mode-hook 'jedi:setup)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.