tags:

views:

183

answers:

2

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.

+6  A: 

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)
Trey Jackson
Thanks, Trey, this opens a whole new set of possibilities ;-)
Dave Paroulek
+4  A: 

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
ddaa
Thanks much, SO comes thru yet again.
Dave Paroulek
I had a (global-set-key "\C-xn" 'other-window) in my .emacs for at least 10 years, had no idea it shadowed those. Thanks.
Trey Jackson