Update: 用新的lsp接口,lsp-mode新接口lsp.el - #6,来自 seagle0128
昨天在这里看到一篇用microsoft python language server的教程,折腾了一下,感觉很不错,在这里分享一下我的配置。
原教程链接:Configuring Emacs, lsp-mode and Microsoft's Visual Studio Code Python language server. - vxlabs
第一步是利用dotnet编译server
- 在这里下载对应平台的dotnet sdk安装, arch linux可以用
sudo pacman -S dotnet-sdk
- 编译server
git clone https://github.com/Microsoft/python-language-server.git
cd python-language-server/src/LanguageServer/Impl
dotnet build -c Release
第二步配置emacs client
;; 编译的server目录
(setq ms-python-dir "/path/python-language-server/output/bin/Release/")
;;; Functions
(defun ms-python--get-python-env()
"Return list with pyver-string and json-encoded list of python search paths."
(let ((python (executable-find python-shell-interpreter))
(ver "import sys; print(f\"{sys.version_info[0]}.{sys.version_info[1]}\");")
(sp (concat "import json; sys.path.insert(0, '" default-directory "'); print(json.dumps(sys.path))")))
(with-temp-buffer
(call-process python nil t nil "-c" (concat ver sp))
(subseq (split-string (buffer-string) "\n") 0 2))))
;; I based most of this on the vs.code implementation:
;; https://github.com/Microsoft/vscode-python/blob/master/src/client/activation/languageServer/languageServer.ts#L219
;; (it still took quite a while to get right, but here we are!)
(defun ms-python--initialization-options ()
"Return initialization-options for LP startup."
(destructuring-bind (pyver pysyspath) (ms-python--get-python-env)
`(:interpreter (
:properties (
:InterpreterPath ,(executable-find python-shell-interpreter)
;;:DatabasePath ,(file-name-as-directory (expand-file-name "db/" ms-python-dir))
:UseDefaultDatabase true
:Version ,pyver))
;; preferredFormat "markdown" or "plaintext"
;; experiment to find what works best -- over here mostly plaintext
:displayOptions (
:preferredFormat "plaintext"
:trimDocumentationLines :json-false
:maxDocumentationLineLength 0
:trimDocumentationText :json-false
:maxDocumentationTextLength 0)
:searchPaths ,(json-read-from-string pysyspath))))
(lsp-register-client
(make-lsp-client
:new-connection (lsp-stdio-connection
(lambda() `("dotnet" ,(concat ms-python-dir "Microsoft.Python.LanguageServer.dll"))))
:major-modes '(python-mode)
:server-id 'ms-python
:initialization-options #'ms-python--initialization-options))
我把上面的代码写到了 ms-python.el中,可以直接下载使用。
运行lsp
激活lsp
几个问题
- 显示文档时空格会显示为 issues/193
- 不支持语法检测,可以用pylint代替
打开python文件时启动lsp
(defun +my-python/enable-lsp()
;; 启动lsp之前启动pyvenv
(unless pyvenv-virtual-env-name
(pyvenv-activate "/home/xhcoding/Code/Python/.venv"))
;; 启动lsp
(lsp)
;; 用pylint检查语法
(setq-local flycheck-checker 'python-pylint)
)
(add-hook 'python-mode-hook #'+my-python/enable-lsp)