I am implementing a custom text object in visual mode, but this text object uses regular expressions to find the beginning and ending of the selection. However, when I do this, other parts of the text are also hilighted. As an additional problem, the searches are added to my search history.

How can these two things be avoided?


I'm trying to creating a visual-mode text object, determining the start and end position using the search backward (?) and search forward (/) operators, similar to the following (the regular expression is just a test for now).

vnoremap ue ?[^a-zA-Z0-9]\\|^<cr>v/[a-zA-Z0-9]\+/e<cr>

When ue is pressed in visual mode:

  1. The above searches backwards for a character that is not a-z, A-Z or 0-9 or until the beginning of the line. This is the text ?[^a-zA-Z0-9]\\|^<cr>.
  2. It then enters visual mode with v.
  3. It then searches forward for the last character that is a-z, A-Z or 0-9. This is text /[a-zA-Z0-9]\+/e<cr>.

The above works fine, but ends up highlighting all characters in the last search expression (step 3). I've tried appending :noh<cr> to the mapping, but this causes the selection to be lost. How can I fix this?

  • Did you look at :h search()?
    – Antony
    May 25, 2017 at 10:39
  • The only complication with search() might be getting it to take a count if that's a requirement.
    – Antony
    May 25, 2017 at 10:46

1 Answer 1


After you turn off search highlighting, use gv to reselect the previous visual selection.

  • Thank you! I ended up using a function because it's easier to read, but gv works, and looks like an excellent little command for my tool belt. Cheers.
    – magnus
    May 27, 2017 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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