In VimScript, How to test if a window is the last window
I'v made a mapping:
nmap: <ESC><ESC&g开发者_运维百科t; :close<CR>
But this mapping can't close the last openned window
So I plan to write a function to test if the current window is the last openned window
Thanks in advance
I use the following to tell if the quickfix windows is the only remaining if so exiting without prompt.
if winbufnr(2) == -1
quit!
endif
Here is my entire code from my .vimrc:
autocmd BufEnter * call MyLastWindow()
function! MyLastWindow()
if &buftype=="quickfix"
" if this window is last on screen quit without warning
if winbufnr(2) == -1
quit!
endif
endif
endfunction
You could modify it to simply do a close if its not the last window and do a quit! if it is. Obviously calling it from your mapping instead of from an autocmd.
Why not just use:
nmap: <ESC><ESC> :quit<CR>
I see it's been mentioned in the comments, but this deserves to be presented as an answer: winnr('$')
. From :help winnr()
The result is a Number, which is the number of the current window. The top window has number 1. When the optional argument is "$", the number of the last window is returned (the window count).
So you could do,
if winnr('$') == 1
" only one window
endif
It has always surprised me that there isn't a native way of finding such information. I have a function that returns the number of open windows by crudely counting them using the windo
command:
fun! NumWindows()
let num_wins = 0
windo let num_wins += 1
return num_wins
endfun
So you have reached the last window when NumWindows() == 1
.
(I think I may have stolen the windo
idea from another thread, but I'm afraid I can't remember which.)
精彩评论