Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: paste search register in command line without brackets

Tags:

vim

Is there a way in Vim to paste the search register on the command-line, but without the surrounding \< brackets \>? I often find myself doing a search in a buffer, and then wanting to use the matched pattern as an argument to grep (more specifically, ack.vim).

Here's what happens if you search for foo and then enter :Ack '<C-r>/':

:Ack '\<foo\>'

This will fail to find anything. What I want instead is:

:Ack 'foo'

This is of course a simplistic example. Where this would be more valuable is with more complex search results.

I am aware of <C-r><C-w> and <C-r><C-a> for pasting the word/WORD under the cursor, and these often suffice, but not always.

like image 420
Jim Stewart Avatar asked Oct 14 '13 21:10

Jim Stewart


People also ask

How to paste from register Vim?

In insert and command-line modes. In insert and command-line modes, you can use <C-R> to paste the contents of a register (:help i_CTRL-R). In particular, <C-R>" pastes from the default (unnamed) register, which is analogous to doing p in normal mode.

How to see register in Vim?

Get the Content of Vim Registers in Insert Mode. If we want to get the content of a register in Insert mode, we can press the “Ctrl-r” followed by the register's name. For example, we want to have the content of “: register in the Insert mode, we press “Ctrl-r” and “:“.


2 Answers

<C-r>/ inserts your search pattern as you typed it: if you did /foo, the search register contains foo.

Note that <C-r>/ inserts the search pattern, not the match: if you search for foo\d, <C-r>/ will insert foo\d, not foo9.

As you found out, \< and \> are added if you used * or # in order to limit the search to whole words. Use g* and g# to not search whole words and thus avoid the \<\>.

Here is a possibly useful mapping:

nnoremap <F6> :Ack '<C-r>=expand("<cword>")<CR>'
like image 185
romainl Avatar answered Oct 17 '22 03:10

romainl


Unless you're doing a purely literal search, there's a difference between the search pattern (a regular expression) and the (list of) matches (strings from the buffer).

If you're interested in the latter, my PatternComplete plugin offers insert-mode completion of all matches, and it can also insert the first match of the last search pattern with <C-R>&.

like image 43
Ingo Karkat Avatar answered Oct 17 '22 02:10

Ingo Karkat