Skip to content

Instantly share code, notes, and snippets.

@jorgenschaefer
Created October 23, 2012 11:29
Show Gist options
  • Save jorgenschaefer/3938289 to your computer and use it in GitHub Desktop.
Save jorgenschaefer/3938289 to your computer and use it in GitHub Desktop.
(defun search-word-at-point ()
"Search and move point to the next occurrence of the word at point."
(interactive)
;; This code is a bit more complex than it should be, mainly to get
;; the "intuitive" result in all cases. `thing-at-point' does not,
;; for example.
(let (beg end word found)
(setq start (point))
(save-excursion
(cond
;; On a word, even on the first char, use the word *after*
;; point, so foo _|_bar finds bar
((looking-at "[[:word:]]")
(forward-word 1)
(setq end (point))
(forward-word -1)
(setq start (point))
(goto-char end))
;; Else, use the word *before* point, so foo_|_ bar finds foo.
(t
(forward-word -1)
(setq start (point))
(forward-word 1)
(setq end (point))))
(setq word (buffer-substring-no-properties start end))
(if (search-forward word nil t)
(setq found (point))
(goto-char (point-min))
(if (search-forward word start t)
(setq found (point))
(error "No other occurrences found"))))
(when found
(goto-char found))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment