0

Given the scenario:

I want to create a vertical split from current buffer for reference another file/the same file. After I've done with this split I don't want to see this buffer-for-reference in the split, but:

  1. If this is a [No Name] buffer, then I'm happy to close this split.
  2. If not, I would like to keep this split to keep the current layout of windows, so I can open up other buffer for reference with the same layout.

Further more, if this is the last window, I'm happy to delete current buffer whether or not it is a [No Name]-buffer.

How to achieve this function in vimscript?

0

I use the following script with assumption:

nnoremap <nowait><silent><expr> ∑                     "(YOUR_SHORT_CUT)
  \ (&filetype=="fern" <bar><bar> &filetype=="startify"
  \  <bar><bar> len(getbufinfo({'buflisted':1}))==1 && &filetype=="")? ":q<CR>":
    \ (winnr('$')==1)? ":bd<CR>":
      \ (&filetype=="")? ":bd<CR>": ":enew<CR>"

Assumption: Every time I do :vsp or :sp, it should create a new [No Name]-buffer, i.e.:

nnoremap <nowait><expr> <C-W><C-H>
    \ ":vsp<CR>".(&filetype==""? ":enew<CR>": "")
nnoremap <nowait><expr> <C-W><C-J>
    \ ":sp<CR><C-W><C-J>".(&filetype==""? ":enew<CR>": "")
nnoremap <nowait><expr> <C-W><C-K>
    \ ":sp<CR>".(&filetype==""? ":enew<CR>": "")
nnoremap <nowait><expr> <C-W><C-L>
    \ ":vsp<CR><C-W><C-L>".(&filetype==""? ":enew<CR>": "")

The scripts can:

  1. If the filetype is MENU / DRAWER: since no buffer for them, use :q.

  2. If it is the last [No Name]-buffer: at this situation we want to quit vim, use :q.

  3. If only one window left: we can delete the buffer without destroy the window-layout, use :bd.

  4. If there are many windows:

    • If it is [No Name]-buffer, by assumption every split create a new [No Name] buffer, so no need to worry about closing multiple [No Name]-buffers at the same time to destroy the layout, use :bd.
    • Otherwise, it's the buffer with which you're done, just :enew and keep the buffer you're done, so no possible to destroy layout(s) when it might also on other split(s).

In short: we only :bd when there is no layout(only one window left) anymore.

Feature: By holding you will close all of them and exit Vim.


Example:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.