Vim - yank into search register
Is there any easy/quick way to "yank" into vim's "last search" register ("/)?
From the vim documentation, it appears that the answer is no, but that it can be assigned via a "let" command:
It is writable with ":let", you can change it to have 'hlsearch' highlight
other matches without actually searching. You can't yank or delete into this
register.
Ideally what I'd like to do is something like:
"/5yw
which would yank the next 5 words under the cursor & put them in the last search buffer
Alter开发者_开发问答natively, if there is a way to search for the contents of a named register, that would work too. In other words, if I could do:
"A5yw
and then search for what is in register A, that would work too.
The closest I can come is to yank into a named register & then copy that register into the last search register, e.g.
"A5yw
:let @/=@A
At the risk of making a long question longer, I want to state that it's not always 5 words I'd like to "yank & search" -- sometimes it's 17 characters, sometimes it's to the end of the line, etc... so a hard-coded macro doesn't give me the flexibility I'd want.
After pressing /
to enter a search string, you can then use Ctrl-R
and then type the letter representing the register that you want to use.
eg.
- First,
"Ayw
to yank a word into register A - Then,
/ ^R A
to put the contents of register A into the search string.
If you did not use any register to store the yanked text vim uses 0
register. You can search for that by typing Ctrl-R 0
after /
.
A more complicated example. Say that you want to search in another buffer for the text inside quotes which is under the cursor right now:
- You can do that with
yi"
(yank inner quote) - Go to the buffer where you want to search
- Type
/Ctrl-R 0
I'm using following code for that:
vnoremap <silent>* <ESC>:call VisualSearch('/')<CR>/<CR>
vnoremap <silent># <ESC>:call VisualSearch('?')<CR>?<CR>
function! VisualSearch(dirrection)
let l:register=@@
normal! gvy
let l:search=escape(@@, '$.*/\[]')
if a:dirrection=='/'
execute 'normal! /'.l:search
else
execute 'normal! ?'.l:search
endif
let @/=l:search
normal! gV
let @@=l:register
endfunction
Searching for a selection:
if you want to first yank a section of a line, then use "v" and move with cursors until you have marked what you want, then press y for yank and now the selection is in register 0
you can then type /Ctrl-R 0
So basically an extended version of the # and * commands, right? It sounds like you want to define a custom operator (a command that expects a motion). I've never actually done this, but I did find a plugin which looks like it might make it easier to do so. There are some examples provided.
精彩评论