Vim Tips Wiki
(→‎Comments: Add user-defined command version)
(Adjust previous/next navigation)
Line 2: Line 2:
 
|id=1063
 
|id=1063
 
|previous=1061
 
|previous=1061
|next=1064
+
|next=1065
 
|created=2005
 
|created=2005
 
|complexity=basic
 
|complexity=basic

Revision as of 02:47, 20 July 2009

Tip 1063 Printable Monobook Previous Next

created 2005 · complexity basic · author zzapper · version 6.0


After searching for text, you can use :g// to list all lines containing the pattern you last searched for. Or, just type g/pattern/ to display all lines containing pattern. This tip shows how to capture the result (the list of all lines that contain the pattern).

Redirecting output

Put the following map in your vimrc. Then, when you are satisfied with the regex you last used for searching, press F3 to output the :g/pattern/ results to a new window.

nmap <F3> :redir @a<CR>:g//<CR>:redir END<CR>:new<CR>:put! a<CR><CR>

Explanation:

:redir @a         redirect output to register a
:g//              repeat last global command
:redir END        end redirection
:new              create new window
:put! a           paste register a into new window

See also

Comments

Send output of last g// to a named file, and open the file:

:nmap <F4> :redir! >/mydir/temp.txt<CR>:g//<CR>:redir END<CR>:new /mydir/temp.txt<CR><CR>

To not get line numbers printed if line numbers are turned on:

" Turn off line numbers, do g//, restore previous state.
:nmap <F3> :let @b=&number<CR>:set nonumber<CR>:redir @a<CR>:g//<CR>:redir END<CR>:let &number=@b<CR>:new<CR>:put! a<CR><CR>

A slightly adapted version to run as a user-defined command:

command! Filter execute 'normal! 0"ay0' | execute 'g//y A' | split | enew | setlocal bt=nofile | put! a
  • execute 'normal! 0"ay0' -- clear the register
  • execute 'g//y A' -- copy all matching lines to the end of the register
  • split | enew | setlocal bt=nofile -- create a new scratch buffer
  • put! a -- paste the contents of the register into the scratch buffer