简体   繁体   中英

How to vim script to execute commands in function

I write new code in my .vimrc (I am very new to vim scripting)

what I want is

Open definition page for word under the cursor to the right side of splited window

so left window is just for index, and right one is for preview (like below picture)

My function intention is

  1. first time open split as vertical window, then do K(in normal mode)
  2. and after first time I close right window and do the same process

but when I invoked function, I got an error 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

What is the wrong code in my function??

在此处输入图片说明

You've expressed your actions as you'd have written a mapping.

You don't need, and must not use <CR> (and <bar> at the end of the line) -- nor :exe -- in your case. And, don't be afraid to write your commands on several lines.

And don't forget to update the variable.

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: line numbers help to understand where the problem is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM