我希望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有什么问题?
答案 0 :(得分:13)
我现在已经确定了一个使用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 documentation以获取自动激活项目虚拟环境的替代方法。简而言之,您可以在项目的根目录中创建.dir-locals.el
文件,其中包含以下内容:
((python-mode . ((project-venv-name . "myproject-env"))))
将"myproject-env"
更改为virtualenv的名称,并使用python-mode
钩子激活虚拟环境:
(add-hook 'python-mode-hook (lambda ()
(hack-local-variables)
(venv-workon project-venv-name)))
(add-hook 'python-mode-hook 'jedi:setup)