Check if current tab is empty in vim

前端 未结 3 1250
南方客
南方客 2021-01-12 20:05

I am writing a vim plugin in which I need to check if the current tab the user is looking at is empty. If it is not empty, like say the user is already viewing a buffer or h

相关标签:
3条回答
  • 2021-01-12 20:42

    The only thing that I can think of for this is to use :windo to iterate through all the windows in the current tab and check whether a file is loaded. Something like this:

    function! TabIsEmpty()
        " Remember which window we're in at the moment
        let initial_win_num = winnr()
    
        let win_count = 0
        " Add the length of the file name on to count:
        " this will be 0 if there is no file name
        windo let win_count += len(expand('%'))
    
        " Go back to the initial window
        exe initial_win_num . "wincmd w"
    
        " Check count
        if win_count == 0
            " Tab page is empty
            return 1
        else
            return 0
        endif
    endfunction
    
    " Test it like this:
    echo TabIsEmpty()
    
    " Use it like this:
    if TabIsEmpty() == 1
        echo "The tab is empty"
    else
        echo "The tab is not empty"
    endif
    

    If the only thing open is a help page or preview window or something like that, it will probably return 1 as I don't think windo operates over those.

    0 讨论(0)
  • 2021-01-12 20:43

    Maybe I'm not understanding the question, but to check if a tab has no buffer do this:

    if bufname("%") == ""
    
    0 讨论(0)
  • 2021-01-12 20:45

    Let's assume that there are multiple windows in the tab, but all the windows' buffers are empty.

    Maybe you'd like to say that this tab is NOT empty. If that's the case, we don't need to go through all the tabs. The following will work.

    function! TabIsEmpty()
        return winnr('$') == 1 && len(expand('%')) == 0 && line2byte(line('$') + 1) <= 2
    endfunction
    
    0 讨论(0)
提交回复
热议问题