Friday, November 02, 2007

Search word at point in Emacs

查找光标上的单词

The default i-search command in Emacs is C-s, and then type the word you want to search. If your cursor is current on the beginning of the word, then you can type C-s C-w. This is case insensitive.

If you want to look for the exact word, then you can use the following code. Type C-* and search the word at the point. It works just like the Star * in VIM.

(defvar my-isearch-word "")

(defun my-isearch-word ()
(interactive)
(when (not mark-active)
(let (word-beg word-end)
(unless (looking-at "\\<")
(if (eq (char-syntax (char-after)) ?w)
(backward-word)
(and (forward-word) (backward-word)))
)
(setq word-beg (point))
(forward-word)
(setq word-end (point))
(setq my-isearch-word (filter-buffer-substring word-beg word-end nil t))
(backward-word)
)
(when (> (length my-isearch-word) 0)
(setq my-isearch-word (concat "\\<" my-isearch-word "\\>"))
(isearch-update-ring my-isearch-word t)
(add-hook 'isearch-mode-end-hook 'my-isearch-word-end-hook)
(isearch-mode t t)
(isearch-repeat 'forward)
(message "%s" isearch-string))))

(global-set-key (kbd "C-*") 'my-isearch-word)

No comments: