How to get a unique identifier for a window?

℡╲_俬逩灬. 提交于 2019-12-22 05:33:36

问题


I am trying to get some sort of unique identifier for a window, so that commands can be run against that window.

Ie, if i need to give that window focus.. or if i need to see the size of that window.. etc. The problem is currently it seems like the window number is used as this identifier, but this number potentially changes any time a new window is introduced.. It seems like it is an index count from left to right and top to bottom.. which puzzles me as to why that would be used as an identifier.

Seeing as i have no idea what the user may do to a layout.. how can i assure that when i assign a window a buffer, or get information about a window, that the i am actually getting information about the window i want?


回答1:


You can use window variables to get such 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 mark all windows. Or, it is maybe better to mark only that windows which you want to use just after window creation. To find a window with id abc and 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"

Most recent Vim versions have win_getid() function and win_id2tabwin() in place of s:FindWinID, also win_gotoid() to just go to window with given identifier. Identifiers are maintained by Vim itself, so even opening window with e.g. noautocmd wincmd s will not be able to create a window without an identifier.




回答2:


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'


来源:https://stackoverflow.com/questions/5215163/how-to-get-a-unique-identifier-for-a-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!