Emacs中python-lsp-server+rope自动补全优先级调整咨询
问题描述
我使用Emacs搭配python-lsp-server(pylsp)进行Python开发,已通过设置lsp-pylsp-plugins-rope-autoimport-enabled启用rope自动导入功能。目前自动补全功能可运行,但自动导入建议常占据补全弹窗前列,挤占本地变量等更相关的补全候选,导致自动导入功能几乎无法正常使用。我希望优先显示本地对象或自有代码的补全建议,或实现按需触发自动导入补全的效果。
查阅rope文档未找到补全排序的相关设置;虽发现pylsp有缺失符号导入的代码动作作为替代,但Emacs的lsp-mode仅将其与补全功能一同启用。先后使用corfu和company作为补全框架,问题均未得到解决。
可复现的最小环境配置
虚拟环境依赖(micromamba,Python 3.12.3)
通过pip安装的包:
black isort python-lsp-server pylsp-mypy python-lsp-ruff pylsp-rope ipython
Emacs 29.3的init.el配置
;; init.el ;; Activate MELPA (require 'package) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) (setq package-menu-hide-low-priority nil) (setq package-archive-priorities '(("gnu" . 20) ("melpa" . 10))) (package-initialize nil) (setq initial-frame-alist '((fullscreen . maximized)) auto-save-default nil inhibit-startup-screen t make-backup-files nil) ;; lsp integration (use-package lsp-mode :ensure :init (setq lsp-ui-doc-show-with-mouse t lsp-ui-doc-position 'at-point lsp-pylsp-plugins-ruff-enabled t lsp-pylsp-plugins-mypy-enabled t lsp-pylsp-plugins-rope-autoimport-enabled t) ; <<<--- For auto-import :hook((python-mode . lsp) (lsp-mode . lsp-enable-which-key-integration)) :commands lsp) ;; completion-at-point framework (`company` works too) (use-package corfu :ensure :demand :custom (corfu-auto t) (corfu-quit-at-boundary 'separator) (corfu-quit-no-match 'separator) (corfu-scroll-margin 0) (corfu-separator ?\s) (corfu-popupinfo-delay '(0.5 . 0.2)) :config (global-corfu-mode) (corfu-popupinfo-mode +1))
解决方案建议
1. 调整pylsp补全排序权重
pylsp支持通过lsp-pylsp-completion-sort-method设置补全排序逻辑,默认是'text'(按文本匹配度),可尝试改为'position'优先显示本地符号:
(setq lsp-pylsp-completion-sort-method 'position)
若该模式不符合预期,可通过lsp-completion-sort-functions自定义排序规则,强制本地候选靠前:
(setq lsp-completion-sort-functions (list (lambda (a b) (let ((a-local (gethash "isLocal" (gethash "data" a))) (b-local (gethash "isLocal" (gethash "data" b)))) (cond ((and a-local (not b-local)) t) ((and (not a-local) b-local) nil) (t (string< (gethash "label" a) (gethash "label" b))))))))
2. 禁用自动补全中的自动导入,改用手动触发
关闭rope自动导入的补全建议,保留代码动作手动触发导入:
(setq lsp-pylsp-plugins-rope-autoimport-enabled nil)
输入未导入的符号后,按M-x lsp-execute-code-action(可绑定快捷键如C-c l a),选择Import missing symbol即可完成导入。
3. 针对Corfu调整补全优先级
Corfu支持通过corfu-sort-function自定义排序逻辑,优先筛选本地候选:
(setq corfu-sort-function (lambda (candidates) (sort candidates (lambda (a b) (let ((a-local (get-text-property 0 'lsp-completion-item-is-local a)) (b-local (get-text-property 0 'lsp-completion-item-is-local b))) (cond ((and a-local (not b-local)) t) ((and (not a-local) b-local) nil) (t (string< a b))))))))
4. 切换至pylsp-jedi插件替代
禁用rope自动导入,改用pylsp-jedi插件(其补全排序更倾向本地符号):
(setq lsp-pylsp-plugins-rope-autoimport-enabled nil) (setq lsp-pylsp-plugins-jedi-completion-enabled t)
需先安装依赖包:pip install pylsp-jedi
内容的提问来源于stack exchange,提问作者Reinhard Stahn

