3

The following function searches buffer text for string STR, in the same way as search-forward. How to modify it in order that it selects the text found?

(defun my-search-forward (str)
  (interactive "smy-search-forward: ")
  (re-search-forward str nil t))
  • For clarification, you meant marking a string and not highlighting it (as in hi-lock-mode), correct? If so, I believe the question and the tag need to be updated. – Kaushal Modi Jul 29 '15 at 2:17
  • @kaushalmodi Thanks, I updated the question. – Name Jul 29 '15 at 7:37
  • There is no such thing (though you can invent it ;-)) as "marking" a string. Presumably you mean selecting text as the active region. That sets the mark at one end of the text, with point at the other end. – Drew Aug 10 '15 at 2:04
9

One way to do it:

(defun my-search-forward (str)
  (interactive "smy-search-forward: ")
  (when (re-search-forward str nil t)
    (setf
     (point) (match-beginning 0)
     (mark) (match-end 0))))
  • 2
    I suggest to wrap the whole thing in a when form for the case nothing is matched. – YoungFrog Aug 10 '15 at 6:56
2

@PythonNut provided a good answer. Another answer is that if you use library Isearch+ (e.g., for other, more important reasons) then you have a user option and commands that let you select the last target occurrence (set the region around it):

  • Option isearchp-set-region-flag -– Non-nil means automatically set the region around the last search target.

  • Command isearchp-toggle-set-region, bound to C-SPC during Isearch -– toggle isearchp-set-region-flag.

  • Command set-region-around-search-target -– manually set the region around the last search target.

So if you set the option to non-nil then Isearch selects the last search hit automatically, by default.

Whether the option is nil or non-nil, you can cause Isearch to select that search hit by using C-SPC before exiting Isearch, if needed.

And if you do not, in one of these ways, cause Isearch to automatically select the last search hit, you can nevertheless select it after exiting Isearch, by using command set-region-around-search-target.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.