How to close a window by window number?

503 views
Skip to first unread message

Eric Siegel

unread,
Jul 23, 2013, 2:49:53 PM7/23/13
to vim...@googlegroups.com
Hi everyone,

I'm attempting to write a small function that toggles a specific buffer. By toggle, I mean quits the window and then splits to reopen it. It is important that I quit the window and not delete the buffer.

I can't seem to find a vim function that allows me to quit a specific window. I have both the buffer name and the window number.

Do I need to iterate over all windows using "wincmd"?

Eric

Gary Johnson

unread,
Jul 23, 2013, 8:01:03 PM7/23/13
to vim...@googlegroups.com
If you have the window number in 'winnr', you can jump to it with

exe winnr . "wincmd w"

or maybe

exe winnr . "wincmd c"

to close it. I haven't tried the last. See

:help :wincmd

Regards,
Gary

Tim Chase

unread,
Jul 23, 2013, 8:20:27 PM7/23/13
to vim...@googlegroups.com, gary...@spocom.com
It does seem a bit anomalous that the last one doesn't work, as most
of the other wincmd accept a prefixed count to specify the window on
which it should act (or the number of windows to traverse).

So you'd have to do a combination of "go there, then close":

:exe winnr . "wincmd w" | wincmd c

This does have the potential to leave you in different window, so you
might want to preserve your current window, jump to the one you want
to close, close it, then jump back to the original. Something like
this (untested) mess:

:let g:oldwinnr=winnr() | exe winnr . "wincmd w" | wincmd c |
exe g:oldwinnr . "wincmd w" | unlet g:oldwinnr

Ugly, but functional.

-tim


Eric Siegel

unread,
Jul 23, 2013, 8:39:15 PM7/23/13
to vim...@googlegroups.com, gary...@spocom.com
Awesome,

Your fix works mostly. The only problem is that the window numbers change after you perform the close. I simply kept the original buffer name around and checked its window after the close.

Thanks everyone for the help!
I can't believe how inconsistent vimscript can be.
We need a standard library.

Eric

Charles Campbell

unread,
Jul 24, 2013, 10:54:28 AM7/24/13
to vim...@googlegroups.com
Eric Siegel wrote:
> Awesome,
>
> Your fix works mostly. The only problem is that the window numbers change after you perform the close. I simply kept the original buffer name around and checked its window after the close.
>
> Thanks everyone for the help!
> I can't believe how inconsistent vimscript can be.
> We need a standard library.
>
I agree that its inconsistent that wincmd c doesn't accept a count.
However, I'd expect that, if it did accept a count, that it would simply
perform [count] window closes, which would not be the same as closing
the window with winnr() of [count].
As far as window numbers changing after the close is performed - that's
what I'd expect.
At least w:vars seem to stick with the logical window that they were
created in.

Regards,
Chip Campbell

Reply all
Reply to author
Forward
0 new messages