[Originally posted by]: http://stackoverflow.com/questions/202803/searching-for-marked-selected-text-in-emacs
I use emacs for viewing and editing code and other text files. I wanted to know if there is a way to search forward or backward for text which is marked in the current buffer. Similar to what I can do in notepad or wordpad. As in can I mark some text in the buffer and do a C-s or C-r and be able to search with the marked text without actually typing in the whole search text?
M-W (to get a copy of the selected text)
C-s <RET> C-y <RET>. Then repeat
C-s as needed. Similarly for
Another option I use quite often is
C-s C-w to search for the word after the current mark. Hitting
C-wrepeatedly increases the search with additional words (e.g.,
C-s C-w C-w C-w searches for the 3 words after the current mark).
C-s C-y searches for the rest of the line after the current mark and
C-s C-M-y searches for the character after the mark. These are both repeatable in the same way.
Other answers describe how to search for copied text, or how to search for the word at point. But none of them actually describe how to “search with the marked text.”
Adding the following hook will make it so that the currently-selected text is the text used for an isearch:
(defun jrh-isearch-with-region () "Use region as the isearch text." (when mark-active (let ((region (funcall region-extract-function nil))) (deactivate-mark) (isearch-push-state) (isearch-yank-string region)))) (add-hook 'isearch-mode-hook #'jrh-isearch-with-region)
Tip: This pairs nicely with expand-region.
There is a great function for this:
isearch-forward-symbol-at-point. It highlights all occurrences of the word where your point is located – no need to place the point at the beginning of the word. Then you can move to next or previous with C-s or C-r.
Note that it is an exact match: if you use it on
hi it won’t match
chill for instance.
I mapped if to
command-f (mac OSX):
(global-set-key (kbd "s-f") 'isearch-forward-symbol-at-point) in the init file.