Technology
 

Toggle to open or close the quickfix window

From Vim Tips Wiki

Tip 1008 Previous Next created October 4, 2005 · complexity basic · author jheddings · version 5.7


Using this function and command:

command -bang -nargs=? QFix call QFixToggle(<bang>0)
function! QFixToggle(forced)
  if exists("g:qfix_win") && a:forced == 0
    cclose
    unlet g:qfix_win
  else
    copen 10
    let g:qfix_win = bufnr("$")
  endif
endfunction

Calling ':QFix' will "toggle" the quickfix open and closed. It's easiest to map this to something fast. I use:

nmap <silent> \` :QFix<CR>

If you want to force the window open, use ':QFix!' and the window will open or stay open.

[edit] Comments

Using autocommands, you can fix the "out-of-sync" issue. The entire code for this would be:

" toggles the quickfix window.
command -bang -nargs=? QFix call QFixToggle(<bang>0)
function! QFixToggle(forced)
  if exists("g:qfix_win") && a:forced == 0
    cclose
  else
    execute "copen " . g:jah_Quickfix_Win_Height
  endif
endfunction

" used to track the quickfix window
augroup QFixToggle
 autocmd!
 autocmd BufWinEnter quickfix let g:qfix_win = bufnr("$")
 autocmd BufWinLeave * if exists("g:qfix_win") && expand("<abuf>") == g:qfix_win | unlet! g:qfix_win | endif
augroup END

I set g:jah_Quickfix_Win_Height in my vimrc to something around 10.


Maybe I'm missing something, but why don't just use :copen and :cclose? Why do you need that function/command?