Search code examples
vimvim-pluginag

Is there a way to insert the current search pattern into commandline?


After installing Ag.vim I've had a frequent need to copy a search from * or / into the command line to search across all files in a codebase.

Example use case:

  1. I find a string of text user_profile_uri and use * to select it.

  2. I press : to enter commandline line mode and enter Ag to start my file search

Is there a way to move or copy the text in my search cursor to the commandline without having to copy the initial text by manually?

Edit:

I'm close to figuring this out. :registers at the commandline will give me a list of registers and while in command mode I can use Ctrl+R <registerkey> to paste. However, the text I need looks like \<user_profile_uri\>


Solution

  • You have a few ways to do this:

    • Insert text from a register via <c-r>{reg}. In this case the search register, /. e.g. <c-r>/
    • You can also insert the word under the cursor via <c-r><c-w>
    • According to the documentation, :h AgFromSearch, you can do :AgFromSearch to run use the current search pattern

    You can combine the :AgFromSearch and * to come up with a mapping to do this all in one step. Add the following to your ~/.vimrc file:

    nnoremap <leader>* *:AgFromSearch<cr>
    

    Now you can use <leader>* to execute your search. The default <leader> is \ so it would become \*. See :h <Leader> for more information.

    For more help see:

    :h c_ctrl-r
    :h c_ctrl-r_ctrl-w
    :h :AgFromSearch
    :h <Leader>
    :h registers
    :h quote/