views:

456

answers:

3

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

Alternatively, 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.

+2  A: 

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.

Jefromi
+9  A: 

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.
ar
This of course works, but it sounds like the OP may not actually want to search, just get the highlighting. If that's the case, a custom operator would be the way to go.
Jefromi
Super - thanks ar... that's exactly what I needed (well, under the constraints that the perfect solution is actually not possible in the first place.) Thanks for the concise solution.
Dan
Dan
@Dan - Ah, cool. If you're obsessive enough to want to cut out the few extra keystrokes, you could still look into the custom operator, but the `^R` method is plenty good - I use it all the time.
Jefromi
+2  A: 

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
Nikolay Frantsev