如何获取窗口的唯一标识符?

Lee*_*var 6 vim

我试图为窗口获取某种唯一标识符,以便可以针对该窗口运行命令.

即,如果我需要给那个窗口焦点..或者如果我需要看到那个窗口的大小..等问题是目前似乎窗口号被用作这个标识符,但这个数字可能随时改变引入了一个新窗口.看起来它是一个从左到右,从上到下的索引计数...这让我很困惑,为什么它会被用作标识符.

看到我不知道用户可能对布局做了什么..我怎么能保证当我指定一个窗口缓冲区,或获取有关窗口的信息时,我实际上获得了有关我想要的窗口的信息?

ZyX*_*ZyX 6

您可以使用窗口变量来获取此类标识符:

" 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
Run Code Online (Sandbox Code Playgroud)

:这应标记所有窗口.或者,最好只在窗口创建后标记要使用的窗口.要查找具有id的窗口,abc然后切换到它:

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"
Run Code Online (Sandbox Code Playgroud)

最新的Vim版本具有win_getid()功能和win_id2tabwin()代替s:FindWinID,也win_gotoid()只是转到具有给定标识符的窗口.标识符由Vim本身维护,因此即使打开窗口,例如noautocmd wincmd s也无法创建没有标识符的窗口.


Foc*_*olf 5

简单版本:

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)
Run Code Online (Sandbox Code Playgroud)

复杂版本:

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'
Run Code Online (Sandbox Code Playgroud)

JonnyRaa:...我发现 win_gotoid 失败并显示有关 winsize 的错误消息

当您忘记将“call”放在“win_gotoid(l:current_window)”前面时,会出现此错误消息。我知道,因为我犯了同样的错误:D

:win_gotoid(123)
E465: :winsize requires two number arguments
Run Code Online (Sandbox Code Playgroud)

应该:

:call win_gotoid(123)
Run Code Online (Sandbox Code Playgroud)

  • 我在没有“call”的情况下使用“win_execute”发现了这个错误! (2认同)