Emacs isearch-forward 默认搜索字符串

3
我有一个关于Emacs Lisp的问题,我想实现这个功能:高亮鼠标下的单词,然后当我按下C-s C-s时,我可以跳到下一个高亮的单词。
所以在我高亮一个单词之后,我希望isearch-string被设置为与我高亮的单词相同,即isearch-forwardisearch-backward命令的默认**搜索字符串可以是我的高亮单词。

我的代码如下:

(defun highlight-current-word()  
  "highlight the word under cursor"
  (interactive)
  (let (head-point tail-point word) 
    (skip-chars-forward "-_A-Za-z0-9")
    (setq tail-point (point))   
    (skip-chars-backward "-_A-Za-z0-9")
    (setq head-point (point))
    (setq word (buffer-substring-no-properties head-point tail-point))
    (setq isearch-string word)      ; no use
    (isearch-search-and-update) ; no use
    (highlight-regexp word 'hi-yellow)))

但它总是提示:[没有先前的搜索字符串]
你能帮我吗?谢谢!


1
你尝试过使用 C-s C-w 吗?这个快捷键可以自动高亮当前单词(或者多个单词,使用更多的 C-w),并且在你使用 C-s(向前搜索)或者 C-r(向后搜索)时,会高亮相同的搜索字符串。 - abiessu
1
我同意abiessu的观点,但如果你使用(thing-at-pt 'word)(或者如果你仍然需要手动删除属性,则使用bounds-of-thing-at-point)获取单词,你也可以简化自己的代码。 - phils
1
那将是 search-ring - juanleon
1
@juanleon,你知道是否有类似于“highlight-regexp-ring”的东西来存储高亮显示的单词历史记录吗? - ruanhao
1
我认为并不是这样(虽然有“regexp-search-ring”,但它与高亮无关) - juanleon
显示剩余2条评论
2个回答

3
我认为你需要在isearch-mode中添加钩子,这样你的函数才能起作用。
(defun highlight-current-word()
  "highlight the word under cursor"
  (interactive)
  (let (head-point tail-point word)
    (skip-chars-forward "-_A-Za-z0-9")
    (setq tail-point (point))
    (skip-chars-backward "-_A-Za-z0-9")
    (setq head-point (point))
    (setq word (buffer-substring-no-properties head-point tail-point))
    (setq isearch-string word)
    (isearch-search-and-update)))

(add-hook 'isearch-mode-hook 'highlight-current-word)

但这会导致您的普通C-s搜索失败,您需要在空格区域或使用M-n/p搜索其他单词。 - gladiator

2
这是您正在寻找的全部内容吗(对我来说不太清楚)?
(defun foo ()
  (interactive)
  (skip-chars-backward "-_A-Za-z0-9")
  (isearch-yank-internal (lambda () (forward-word 1) (point))))

(define-key isearch-mode-map (kbd "C-o") 'foo)

这个命令类似于 C-w,但它会选中光标所在的整个单词,而不仅仅是从光标到单词结尾的文本。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接