giving region to search in emacs

491 Views Asked by At

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

2

There are 2 best solutions below

1
On BEST ANSWER

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)))
0
On

This is exactly what is available with Isearch+ (isearch+.el). Whether searching is restricted to the active region is controlled by Boolean option isearchp-restrict-to-region-flag.

You can use C-x n (command isearchp-toggle-region-restriction) during search to toggle this behavior.

A second Boolean option, isearchp-deactivate-region-flag, controls whether the region is to be deactivated during search (e.g., so you can better see the search region).

Both options are true by default (search is restricted to the active region, and the region is deactivated during search).

(For Isearch to be limited to the active region in Info, you must also use library Info+ (info+.el).


UPDATE

Well, it was exactly what you described initially. Your later reply to comments shows that you do not in fact want to search the text in the region; you want to search for the text in the region, elsewhere in the buffer. This does the former, not the latter.