How to create a key map to open and close the quickfix window in Vim

In sufficiently new versions of vim (where getwininfo is available), try:

function! ToggleQuickFix()
    if empty(filter(getwininfo(), 'v:val.quickfix'))
        copen
    else
        cclose
    endif
endfunction

nnoremap <silent> <F2> :call ToggleQuickFix()<cr>

Customizations,

  • TO open the window in a vertical pane, vertical copen
  • For the location list (instead of quick fix), replace copen/cclose with lopen/lclose, and v:val.quickfix with v:val.loclist.)

There is a vim plugin: https://github.com/milkypostman/vim-togglelist


Here is another way to do it, probably skipping some gory details but it works:

function! ToggleQuickFix()
  if exists("g:qwindow")
    lclose
    unlet g:qwindow
  else
    try
      lopen 10
      let g:qwindow = 1
    catch 
      echo "No Errors found!"
    endtry
  endif
endfunction

nmap <script> <silent> <F2> :call ToggleQuickFix()<CR>

If there are no errors the lopen will not work so I try catch that, in case there is it opens the window and creates a variable. then if it doesn't it just closes it.

The cool thing is that this approach can be used to everything you would like to toggle.

Tags:

Vi

Vim