如何通过vim脚本执行功能中的命令 我想要的是我的意图是

问题描述

我在.vimrc中写了新代码(我对vim脚本非常陌生)

我想要的是

在拆分窗口右侧的光标下打开单词的定义页面

所以左边的窗口仅用于索引,右边的窗口用于预览(如下面的图片所示)

我的意图是

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

但是当我调用函数时,出现了错误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

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

enter image description here

解决方法

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

您不需要,也不能使用<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:行号有助于了解问题所在。