Searching for marked (selected) text in Emacs

Yes. M-W (to get a copy of the selected text) C-s <RET> C-y <RET>. Then repeat C-s as needed. Similarly for C-r.


I am using the following which does not have the problem of having to type more then one successive C-s to find later occurences:

    (defun search-selection (beg end)
      "search for selected text"
      (interactive "r")
      (kill-ring-save beg end)
      (isearch-mode t nil nil nil)
      (isearch-yank-pop)
    )
    (define-key global-map (kbd "<C-f3>") 'search-selection)

The disadvantage of the previous code is that the selected text is copied to the stretch. The following code does not have this problem:

    (defun search-selection (beg end)
      "search for selected text"
      (interactive "r")
      (let (
            (selection (buffer-substring-no-properties beg end))
           )
        (deactivate-mark)
        (isearch-mode t nil nil nil)
        (isearch-yank-string selection)
      )
    )
    (define-key global-map (kbd "<C-f3>") 'search-selection)

@Alex nails it.

Another option I use quite often is C-s C-w to search for the word after the current mark. Hitting C-w repeatedly 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).

Similarly, C-s M-s C-e 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 (the former by somewhat-awkwardly repeating M-s C-e after C-s).


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.