How to get a unique identifier for a window?

I am trying to get some unique identifier for a window so that commands can run against this window.

That is, if I need to specify this window focus or if I need to see the size of this window ... etc. Currently, the problem is that the window number is used as this identifier, but this number potentially changes at any time when a new window is entered. It looks like it's an index account from left to right and top to bottom .. which puzzles me why this will be used as an identifier.

Seeing how I have no idea what the user can do with the layout. How can I assure that when I assign a window to a buffer or get window information, I actually get the window information I want?

+3
source share
2 answers

You can use window variables to get this identifier:

" put unique window identifier into w:id variable
autocmd VimEnter,WinEnter * if !exists('w:id') | let w:id={expr_that_will_return_an_unique_identifier} | endif

: this should mean all windows. Or perhaps it’s better to check only those windows that you want to use immediately after creating the window. To find the window with id abc, then switch to it:

function s:FindWinID(id)
    for tabnr in range(1, tabpagenr('$'))
        for winnr in range(1, tabpagewinnr(tabnr, '$'))
            if gettabwinvar(tabnr, winnr, 'id') is a:id
                return [tabnr, winnr]
            endif
        endfor
    endfor
    return [0, 0]
endfunction
<...>
let [tabnr, winnr]=s:FindWinID('abc')
execute "tabnext" tabnr
execute winnr."wincmd w"

In recent versions of Vim there is a function win_getid()both win_id2tabwin()instead of s:FindWinID, and also win_gotoid(), just to go to the window with the given identifier. Identifiers are supported by Vim itself, so even an opening window, for example, noautocmd wincmd scannot create a window without an identifier.

+5
source
Simple version:

    let l:current_window = win_getid()

    ... do something that alters the current window and/or tab and now i want to go back

    call win_gotoid(l:current_window)

Complicated version:

    let [l:current_window_tabnr, l:current_window_winnr] = win_id2tabwin(win_getid())

    or

    let l:current_window_tabnr = tabpagenr()
    let l:current_window_winnr = winnr()

    ... do something that alters the current window and/or tab and now i want to go back

    execute 'tabnext ' . l:current_window_tabnr
    execute l:current_window_winnr . 'wincmd w'
+1
source

Source: https://habr.com/ru/post/1796716/


All Articles