Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM: Close all other tabs of current file except the one I'm on?

Tags:

vim

Say if my 5 open tabs are:

file1 file2 file2 file2 file3

I want a quick way to close just all of the duplicate file2 tabs, when the focus is on any of the file2 tabs.

So result after running command should be:

file1 file2 file3

The command should not have any effect when focus is on file1 or file3 as there're no duplicate tabs of these.

Any thoughts on how to achieve this?

EDIT - SOLUTION based on Ingo's suggestions:

function! s:CloseDupTabs()
    let curBufnr = bufnr('')
    let numTabs  = tabpagenr('$')

    " Run for 1 lesser than numTabs so that we don't visit current tab in loop
    for i in range(numTabs - 1)
        execute 'tabnext'

        if curBufnr == bufnr('')
            " Check edge case to see if we're already on last tab before doing tabprev
            if tabpagenr() != tabpagenr('$')
                close 
                execute 'tabprev'
            else
                close
            endif
        endif
    endfor

    execute 'tabnext'
endfunction
like image 898
Prasanna UV Avatar asked Dec 11 '25 18:12

Prasanna UV


1 Answers

Every open file in Vim gets a unique buffer number; the one for your current file (file2 in your example) can be obtained via

:let bufnr = bufnr('')

You can then inspect the other tab pages, and close any buffer with the same number there. :help tabpagebuflist() has an example how to iterate over all tab pages; just modify that to skip the current (tabpagenr()) one.

In order to close a buffer, you first need to navigate to the corresponding tab page:

:execute 'tabnext' tabnr

If you always have just one window in a tab, you can then just :close it. Else, you need to first find the window that has the buffer, and go to it:

:execute bufwinnr(bufnr) . 'wincmd w'

It would be nice to keep track of the original tab page number, decrementing it when removing tab pages before it, in order to return to the original one.

like image 82
Ingo Karkat Avatar answered Dec 14 '25 18:12

Ingo Karkat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!