1. 需求分析
- 目标:在按 M-x 时,自动获取光标所在单词(如 suggestCourse 或 考试系统)作为 M-x 的初始输入。
- 场景:
- Java 代码:光标在 suggestCourse,希望 M-x 预填 suggestCourse。
- Org-mode:光标在 考试系统,预填到 minibuffer。
- 结合 amx(您之前的问题),优化命令选择。
- 挑战:
- M-x 默认不捕获光标单词。
- 需要自定义函数或绑定,兼容 java-mode、org-mode 等。
方法 1:自定义函数获取光标单词并调用 M-x
创建一个函数,捕获光标下的单词并将其作为 M-x 的初始输入。
步骤
- 定义函数:
(defun my-amx-with-word-at-point ()
"Run amx with word, symbol, or Chinese text at point."
(interactive)
(let ((word (or (thing-at-point 'word t)
(thing-at-point 'symbol t)
(let ((bounds (bounds-of-thing-at-point 'sexp)))
(when bounds
(buffer-substring-no-properties
(car bounds) (cdr bounds))))
"")))
(minibuffer-with-setup-hook
(lambda ()
(unless (string-empty-p word)
(insert word)))
(amx))))
(global-set-key (kbd "C-c x") 'my-amx-with-word-at-point)
步骤
- 确保 amx 安装:
- 在 init.el:
(use-package amx
:ensure t
:config
(amx-mode 1))
- 修改函数支持 amx:
- 更新函数:
(defun my-amx-with-word-at-point ()
"Run amx with the word at point as initial input."
(interactive)
(let ((word (thing-at-point 'word t)))
(minibuffer-with-setup-hook
(lambda ()
(when word
(insert word)))
(amx))))
- 绑定快捷键:
- 在 init.el:
(global-set-key (kbd "C-c x") 'my-amx-with-word-at-point)
- 测试:
- 光标在 org-roam-node-find(Org 文件):
- org-roam-node-find
- 按 C-c x:
- Minibuffer 显示:org-roam-node-find,amx 补全相关命令。
适用场景
- 使用 amx 的模糊匹配,快速选择命令。