FANDOM


This is a little function you can use to quickly filter a whole buffer for a term, with a convenient shortcut for the term you just searched for (available in register @/). It's similar to the search function in e.g. mutt or mocp, only the output is written to a scratch buffer rather than modifying the current buffer. If you want the former behaviour, use an Ex command like :v/EXP/d, which deletes all lines that don't match EXP.

  function! Gather( line_pattern )
    if empty(a:line_pattern)
      return
    endif

    " fill gather list, return if there are no results
    let gather_list = []
    let l:orig = getpos(".")
    let l:orig_ft = &ft
    execute "g/" . a:line_pattern . "/call insert(gather_list, getline(\".\"))"
    call setpos(".", l:orig)
    if empty(gather_list)
      return
    endif

    " create new scratch buffer
    new
    setlocal buftype=nofile
    setlocal bufhidden=hide
    setlocal noswapfile
    execute "setlocal filetype=".l:orig_ft

    " copy all results in the new scratch buffer
    for line in gather_list
      call append(0, line)
    endfor
    normal ddgg
    unlet gather_list
  endfunction

This function can be used to quickly close a scratch buffer. I mapped it to <Esc> in normal mode, so that's the keystroke this function defaults to if the current buffer is not a scratch buffer. We don't want to close "real" buffers that easy. You might want to change that line to the key you're mapping this function onto.

 function! CloseScratch()
   if &buftype == "nofile" && &bufhidden == "hide" && !&swapfile 
     " this is a scratch buffer
     bdelete
   else
     " this is not a scratch buffer
     normal! "<Esc>"
   endif
 endfunction

And finally some key mappings to make it all available. I'm using , as a mapleader and find using "generic" binding such as execute "nmap" g:mapleader."f :call Whatever()<CR>" not very readable in my vimrc. Adjust as needed.

 nmap ,f :call Gather( input("Filter on term: ") )<CR>
 nmap ,F :call Gather( @/ )<CR>
 nmap <Esc> :call CloseScratch()<CR>

In this case, ,f asks the user for input, ,F re-uses the search register.

Niels AdB

Community content is available under CC-BY-SA unless otherwise noted.