Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim close buffer but not split window

Tags:

vim

buffer

If I have 2 buffers split horizontally/vertically and want to close one of them, but i don't want to close a window. I want to keep places of split windows are the same as before closing buffer.

If I press :bd , the window in which was closed buffer also became closed.

like image 561
RusAlex Avatar asked Nov 28 '10 20:11

RusAlex


1 Answers

Like @RusAlex I don't like plug-ins. I also like to know what code I enter actually does.

nmap ,d :b#<bar>bd#<CR>

In short this adds a key mapping to vim's normal mode waiting for key sequence ,d. When executed this switches to a previously open buffer and attempts to delete the buffer you switched away from.

Deleting an off-screen buffer keeps the screen split as it is.

The command consists of three space-separated parts:

  • nmap - add/change key mapping for mode normal
  • ,d - key sequence to react to; first , (comma), then d
  • :b#<bar>bd#<CR> - key sequence to execute

The command to be executed consists of five parts:

  • : - switch vim to mode command-line
  • b# - switch window to previously open buffer
  • <bar> - expect a follow-up command; represents | (pipe character); used for chaining commands
  • bd# - delete previously open buffer, i.e. the buffer just switched away from
  • <CR> - execute command(s); represents carriage return, basically the keys Return or Enter

The command is in the format it is used in a configuration file like ~/.vimrc. If you want to add the mapping from within vim you prepend : (colon) - the mapping then will be lost when exiting vim:

:nmap ,d :b#<bar>bd#<CR>

When you open vim it is usually in normal mode as opposed to modes insert (indicated on the bottom of the screen by -- INSERT -- after pressing i), visual and so on. The n in nmap specifies the key mapping to be added to normal mode only. Find more on mappings here

Important notes:

  • b# will switch to the current buffer if it is the only known buffer.
  • b# may switch to a hidden/closed buffer, e.g. the one you just closed by pressing ,d.
  • bd# will close the current buffer if it is the only known buffer unsplitting the screen leaving you with an empty buffer.
  • bd# will fail if the buffer switched away from is a hidden/closed buffer.
  • bd# will still unsplit if after switching another window shows the buffer to close.

Additional notes:

  • :windo b# will switch all windows to the previously open buffer. Not sure how to combine with bd.
  • <CR> can be left out in which case you have to manually press Return or Enter to execute.
  • :nmap , displays all normal mode mappings starting with ,.
  • :ls lists open buffers.
like image 71
valid Avatar answered Sep 21 '22 01:09

valid