如何vim脚本在函数中执行命令

How to vim script to execute commands in function

我在 .vimrc 中编写了新代码(我对 vim 脚本编写还很陌生)

我想要的是

打开拆分右侧光标下的词的定义页window

所以左边window只是索引,右边是预览(如下图)

我的函数意图是

  1. 第一次打开拆分为垂直window,然后执行 K(在正常模式下)
  2. 第一次后我关闭右 window 并执行相同的过程

但是当我调用函数时,出现错误Invalid argument

nnoremap <Leader><CR> :call Goto_definition() <CR>

let g:first_open=0
function! Goto_definition() 
    if g:first_open
        :vs <bar> :wincmd l <CR> // 1. vertical split and go to right window
        :exe 'normal K'          // 2. then press shortcut K (in normal mode)
        let g:first_open=0       // 3. set variable
    else 
        :wincmd l<bar> :q<bar>  // 4 .close right window first (because it's not a first time)
        :vs <bar> :wincmd l <CR> // repeat step 1~3 
        :exe 'normal K'
    endif
endfunction

我的函数中有什么错误的代码??

您已经像编写映射一样表达了您的行为。

您不需要,也不能在您的情况下使用 <CR>(和行尾的 <bar>),也不能使用 :exe。而且,不要害怕在多行中编写命令。

别忘了更新变量。

nnoremap <Leader><CR> :<c-u>call <sid>Goto_definition()<CR>

let s:first_open = get(s:, 'first_open', 0) " set to 0 the first time, keep the old value when resourcing the plugin

function! s:Goto_definition() abort
    if ! s:first_open
        wincmd l
        q
    endif

    " Looks like the following steps shall always be executed.
    rightbelow vs " same as vs + wincmd l
    normal K
    " with a K command (which doesn't exist), it could have been done with: "rightbelow vs +K"

    let s:first_open = 1 - s:first_open
endfunction

PS:行号有​​助于了解问题出在哪里。