Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

vi

If I use :lopen, Vim opens the quickfix window, and if I use :lcl on the window with errors (or the quickfix window itself), it closes it.

What I want to do in my .vimrc is to create a map that opens the quickfix like this:

nnoremap <F2> :lopen 10<CR>

but when I press F2 again it closes it using :lcl.

Is there a way to know if the quickfix window is open and then execute the :lcl?

like image 964
Hassek Avatar asked Jun 25 '12 22:06

Hassek


3 Answers

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.)
like image 52
tckmn Avatar answered Oct 12 '22 19:10

tckmn


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

like image 42
kev Avatar answered Oct 12 '22 19:10

kev


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.

like image 44
Hassek Avatar answered Oct 12 '22 21:10

Hassek