Emacs: Search Current Word 💠

By Xah Lee. Date: . Last updated: .

Command to Search Current Word

Here's a command to isearch the word under cursor.

(defun xah-search-current-word ()
  "Call `isearch' on current word or selection.
“word” here is A to Z, a to z, and hyphen [-] and lowline [_], independent of syntax table.

URL `http://xahlee.info/emacs/emacs/modernization_isearch.html'
Created: 2010-05-29
Version: 2025-02-05"
  (interactive)
  (let (xbeg xend)
    (if (region-active-p)
        (setq xbeg (region-beginning) xend (region-end))
      (save-excursion
        (skip-chars-backward "-_A-Za-z0-9")
        (setq xbeg (point))
        (right-char)
        (skip-chars-forward "-_A-Za-z0-9")
        (setq xend (point))))
    (when (< xbeg (point)) (goto-char xbeg))
    (isearch-mode t)
    (isearch-yank-string (buffer-substring-no-properties xbeg xend))))

You need to give it a easy key. Such as F8. 〔see Emacs Keys: Define Key

Also, you should set your isearch repeat to arrow keys. Emacs Init: isearch by Arrow Keys.

Problem with Emacs's isearch

Emacs's “isearch” command have inconvenience problem of searching the current word.

Suppose you have this line:

aa-bb-▮cc xx yy

and your cursor is on the second hyphen. You want to search the next occurrence of the word “aa-bb-cc”. You have to press Alt+b Alt+b Ctrl+s Ctrl+w Ctrl+w Ctrl+w Ctrl+s. That's about 8 keys. In vim, it's just a single key press *.

2014-03-11 addendum: Emacs 24.4 (date 2014-10) has the new command isearch-forward-symbol-at-point that improved the situation but still pretty bad. Now to search current word under cursor, you need to press Alt+s . Alt+s _ Ctrl+s. [see Emacs: Search Text in Current File] Besides the too-many-keys problem, this command has more problems:

  1. isearch-forward-symbol-at-point is on “symbols” only. What chars are part of “symbol” is unpredictable, mode-dependent.
  2. The search is with boundary check. That is, if current symbol is “xx”, it'll will not find occurrences of “xx2”.

Emacs Find Replace

Emacs Modernization