sponsor Vim development Vim logo Vim Book Ad

basic Tip #1078: Best way to close (delete) buffer without closing its window

 tip karma   Rating 114/36, Viewed by 4512 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   December 14, 2005 12:13      complexity:   basic
author:   Matt Zyzik      as of Vim:   6.0

"delete the buffer; keep windows
function Kwbd(kwbdStage)
if(a:kwbdStage == 1)
let g:kwbdBufNum = bufnr("%")
let g:kwbdWinNum = winnr()
windo call Kwbd(2)
execute "bd! " . g:kwbdBufNum
execute "normal " . g:kwbdWinNum . ""
else
if(bufnr("%") == g:kwbdBufNum)
let prevbufvar = bufnr("#")
if(prevbufvar > 0 && buflisted(prevbufvar) && prevbufvar != g:kwbdBufNum)
b #
else
bn
endif
endif
endif
endfunction

-- That's a very simple function I wrote to enable someone to close the current buffer (like :bd) yet not close any associated windows with that buffer. I haven't seen anything easier and/or simpler than this. To use this function, just do :call Kwbd(1)

 rate this tip  Life Changing Helpful Unfulfilling 

<< Move Function Parameters with macro | map <F3> to find exactly one word >>

Additional Notes

Christian J. Robinson, December 14, 2005 17:28
You might find vimscript #559 useful as well.
Matt Zyzik, December 14, 2005 18:40
Actually that script is not useful because it doesn't work. Try closing a buffer that's open in several windows and see what happens... the windows close.
Matt Zyzik, December 15, 2005 7:53
Developers should note the "windo call" command. windo will execute a command on all open windows.
amix at amix.dk, December 15, 2005 14:22
check out vimtip #165 also - it's on the same topic
NdrOchip@ScampbellPfamily.AbizM - NOSPAM, December 16, 2005 8:17
Deleting a buffer without changing your window layout, vimtip#622, is also on the same topic.  I don't believe my tip, however, covered the multiple windows on the same buffer issue.
Matt Zyzik, December 16, 2005 20:05
Right so people should note that none of the above scripts/tips actually work in preserving all windows that contain the buffer being deleted. My script doesn't have this problem, because it has that windo call, which executes a command on all open windows.
yeah!!!, December 23, 2005 13:26
this is awesome
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to the maillist. Help Bram help Uganda.
   
Sponsored by Web Concept Group Inc. SourceForge.net Logo