Search code examples
emacselisp

emacs isearch-forward default search string


I have a question about Emacs Lisp, I want to achieve this functionality: ‘highlight a word under cursor, then when I push C-s C-s, I can jump to the next highlighted word’.
So after I highlight a word, I hope the isearch-string can be set as the same as the word I have high lightened, i.e. the default ** search string for command **isearch-forward or isearch-backward can be my highlighted word.

My code is like:

(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)))

But it always prompts: [No previous search string]
Can you help me? Thank you!


Solution

  • I think you need add hook to isearch-mode, then your function will be work.

    (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)