user
user

Reputation: 5380

Exact selected multiline string search in vim

I have a buffer. In that buffer exists a string that spans multiple lines:

asdf
qrughatuxlnjtzu
... tens more lines...

I have one instance of this string readily available under my cursor. I want to search for other instances of this multiline string in the same buffer without having to manually copy/edit significant portions of said multiline string into the command buffer (n.b. manually replacing newlines with their regex equivalents is significant editing).

I've tried using How do I search for the selected text? (visual selection -> yank -> command buffer) + Exact string match in vim? (Like 'regex-off' mode in less.) (verbatim search), but the approaches do not appear to work for multiple lines.

How do I perform an exact multiline search of a selected string in Vim?

Upvotes: 1

Views: 1107

Answers (4)

zzami
zzami

Reputation: 16

I'd map * to search visual selected region with this:

vnoremap * "vy/\V<C-R>=substitute(escape(@v,'/\'),'\n','\\n','g')<CR><CR>

Upvotes: 0

Fabius Wiesner
Fabius Wiesner

Reputation: 926

nnoremap <your keys> :<c-u>let @/=@"<cr>gvy:let [@/,@"]=[@",@/]<cr>/\V<c-r>=substitute(escape(@/,'/\'),'\n','\\n','g')<cr><cr>

Then visually select the lines with V (or v for part of lines), and then hit <ESC> and <your keys>.

Source is here (see answer by @Peter Rincker).

Upvotes: 2

Spangen
Spangen

Reputation: 4720

Depending on the newline characters that are in your file you can include the end of line characters in your search too,

e.g. for Unix line endings you can search for

/asdf\nqrughatuxlnjtzu$

for windows line endings you'd use \r\n instead.

The $ character above will search to the end of the line so will exclude any line endings but this is necessary to avoid matching on lines such as

asdf
qrughatuxlnjtzuNotToBeMatched

Also see http://vim.wikia.com/wiki/Search_across_multiple_lines

Upvotes: 0

B.G.
B.G.

Reputation: 6016

You could just search with \n as newline:

/asdf\nqrughatuxlnjtzu

Upvotes: 0

Related Questions