Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emacs newbie question - how to search within a region

Tags:

search

emacs

If I select a region of text, is there a way to use isearch (or some other search command) that will allow me to only search within the region? I was hoping to use this to technique inside a macro.

This might be obvious, but I did a quick search and couldn't find a way.

like image 975
Upgradingdave Avatar asked Dec 12 '09 15:12

Upgradingdave


2 Answers

You can use this combination of commands:

M-x narrow-to-region
C-s SOMETEXT
M-x widen

Though, that's kind of burdensome, here's a new command that does the above for you automatically.

(defun isearch-forward-region-cleanup ()
  "turn off variable, widen"
  (if isearch-forward-region
      (widen))
  (setq isearch-forward-region nil))

(defvar isearch-forward-region nil
  "variable used to indicate we're in region search")

(add-hook 'isearch-mode-end-hook 'isearch-forward-region-cleanup)

(defun isearch-forward-region (&optional regexp-p no-recursive-edit)
  "Do an isearch-forward, but narrow to region first."
  (interactive "P\np")
  (narrow-to-region (point) (mark))
  (goto-char (point-min))
  (setq isearch-forward-region t)
  (isearch-mode t (not (null regexp-p)) nil (not no-recursive-edit)))

Now just do M-x isearch-forward-region RET SOMETEXT, or bind it to a key binding of your preference like:

(global-set-key (kbd "C-S-s") 'isearch-forward-region)
like image 50
Trey Jackson Avatar answered Nov 13 '22 11:11

Trey Jackson


As Trey Jackson said, you can use narrow-to-region and widen. I'll chip in for the keyboard shortcuts. Note that they are disabled by default, and emacs will interactively prompt to "undisable" them on the first use.

C-x n n
C-s sometext
C-x n w
like image 26
ddaa Avatar answered Nov 13 '22 13:11

ddaa