sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #340: Visual Select And Search

 tip karma   Rating 13/4, Viewed by 1610 

created:   October 10, 2002 18:59      complexity:   intermediate
author:   Chris Butler (cz_butler@yahoo.com)      as of Vim:   6.0

The following visual select and search map is a combination of information
from Benji's vimrc file (vmap S y/<C-R>=escape(@",'/')<CR>) and a tip that
mentions the "\n" to "\\\\n" substitution.

It works for special characters and multiple lines.

vmap \s y/\V<C-R>=substitute(escape(@",'/'),"\n","\\\\n","g")<CR>/<CR>

Quick explanation:

vmap       visual map
\s         your choice
y          yank selected text
/          search delimiter
\V         no magic, just text
<C-R>=     expression
substitute substitute "\n" for "\\\\n"
escape     escape '/' (delimiter) and '' in yanked text (@")
<CR>       end expression
/<CR>      search

Warning: Folding will not match if the foldexpr expression is using
getline() to match against a search pattern that spans multiple lines.

Enjoy.

 rate this tip  Life Changing Helpful Unfulfilling 

<<"tabbed windows" | switch color schemes >>

Additional Notes

Chris Butler, October 11, 2002 14:23
Sorry, something was lost when I pasted it (besides the line format :)

The substitute string is '/' - that's forward slash + backward slash.
One needs to escape any '' (backslash) to nulify any specials.
Chris Butler, October 11, 2002 14:25
Let try that again ...

Sorry, something was lost when I pasted it (besides the line format :)

The substitute string is '/\' - that's forward slash + backward slash.
One needs to escape any '\' (backslash) to nulify any specials.
David Fishburn, June 4, 2003 5:51
I have this in my vimrc file.
It will deal with correctly escaping the string you have visually selected.
This was hashed out on the vim mailing list a few months back, and this is the final version.
It also maintains the register we pull the text into.

" Courtesy of Michael Naumann, Jürgen Krämer
" Visually select text, then search for it, forwards or backwards
vmap <silent> * :<C-U>let old_reg=@"<cr>
                  \gvy/<C-R><C-R>=substitute(
                  \escape(@", '\\/.*$^~[]'), "\n$", "", "")<CR><CR>
                  \:let @"=old_reg<cr>
vmap <silent> # :<C-U>let old_reg=@"<cr>
                  \gvy?<C-R><C-R>=substitute(
                  \escape(@", '\\/.*$^~[]'), "\n$", "", "")<CR><CR>
                  \:let @"=old_reg<cr>
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to vim@vim.org after searching the archive. Help Bram help Uganda.
Sponsored by Web Concept Group Inc. SourceForge Logo