Search code examples
emacsisearch

giving region to search in emacs


Is there a way to provide a region to isearch?

I want to overload isearch so that:

C-s -> 1. isearch as usual if no region is selected, OR 2. isearch with region as to-be-used-for-search string

example: i 'select' the words "no exit", then C-s should search the buffer for "no exit". In a way this can be done with C-s C-w C-w when the cursor is at the beginning of "no". I wonder if there is a way to reverse this, so first select (some how) and then use the selection for searching


Solution

  • You may find the commands narrow-to-region and widen useful, do C-hfnarrow-to-regionRET and C-hfwidenRET to know more

    UPDATE

    Here is some quick and dirty code to do what you want, I have not handled some cases for simplicity but this should give an idea

    (add-hook 'isearch-mode-end-hook (lambda ()
                                       (when (buffer-narrowed-p)
                                         (widen))))
    
    (defun my-isearch(&optional start end)
      (interactive "r")
      (when (region-active-p)
          (narrow-to-region start end))
        (call-interactively 'isearch-forward-regexp))
    

    UPDATE 2

    Try the following function, this should do what you want

    (defun my-isearch(&optional start end)
      (interactive "r")
      (if (region-active-p)
          (progn
            (let ((string (buffer-substring-no-properties start end)))
              (deactivate-mark)
              (isearch-resume string nil nil t string nil)))
        (call-interactively 'isearch-forward-regexp)))