How can I close a buffer without closing the window?

前端 未结 16 992
鱼传尺愫
鱼传尺愫 2020-12-12 13:35

Vim\'s multilayered views (Windows, Buffers and Tabs) left me a little confused. Let\'s say I split the display (:sp) and then select a different buffer to display in each w

16条回答
  •  攒了一身酷
    2020-12-12 14:06

    Here is a very readable vimscript function, which handles all cases well,

    • behave similar to built-in:bd (if only one window, just invoke it!),
      • issue a warning and do nothing if buffer modifed.
      • if no other buffer, create one, via :enew.
      • if alternate buffer exist and in buffer-list, switch to it, else go next, via:bn.
    • more reasonable behavior for multiple-window layout
      • not closing any window,
      • always stay on the original window.
      • for each window that displays current buffer, do as listed above, then delete old current buffer.
    nnoremap b :call DeleteCurBufferNotCloseWindow()
    
    func! DeleteCurBufferNotCloseWindow() abort
        if &modified
            echohl ErrorMsg
            echom "E89: no write since last change"
            echohl None
        elseif winnr('$') == 1
            bd
        else  " multiple window
            let oldbuf = bufnr('%')
            let oldwin = winnr()
            while 1   " all windows that display oldbuf will remain open
                if buflisted(bufnr('#'))
                    b#
                else
                    bn
                    let curbuf = bufnr('%')
                    if curbuf == oldbuf
                        enew    " oldbuf is the only buffer, create one
                    endif
                endif
                let win = bufwinnr(oldbuf)
                if win == -1
                    break
                else        " there are other window that display oldbuf
                    exec win 'wincmd w'
                endif
            endwhile
            " delete oldbuf and restore window to oldwin
            exec oldbuf 'bd'
            exec oldwin 'wincmd w'
        endif
    endfunc
    

提交回复
热议问题