如何设置 vimscript 命令来调用函数?

Non*_*ona 2 vim

所以我希望能够输入如下内容:

:你好

在 vim 正常模式下,然后让它回显“你好先生”。

我把下面的 vimscript 变成了一个插件,我得到了错误:

不是编辑器命令

我究竟做错了什么?

脚本

if exists("g:hello_world") || &cp || v:version < 700 
  finish
endif
let g:hello_world=1 " your version number
let s:keepcpo = &cpo
set cpo&vim

fun! s:hellosir()
  echo 'hello sir'
endfun

command hello call hellosir()
Run Code Online (Sandbox Code Playgroud)

ste*_*fen 8

定义您的函数(请注意用户定义函数的大写字母):

:fun! Hellosir()
:    echo 'hello sir'
:endfun
Run Code Online (Sandbox Code Playgroud)

现在称其为:

:call Hellosir()
Run Code Online (Sandbox Code Playgroud)

hello sir

也可以定义自己的 ex 命令:

:command Hello :call Hellosir()
:Hello
Run Code Online (Sandbox Code Playgroud)

hello sir

编辑

您可以将两者结合起来:将函数设置为本地脚本并使用(全局)ex 命令访问它:

fun! s:hellosir()
  echo 'hello sir'
endfun
command Hello call s:hellosir()
Run Code Online (Sandbox Code Playgroud)


pio*_*ojo 6

steffen 的回答是正确的,但这里有一个带有参数的示例:

" a highlight color must be set up for the function to work
highlight blue ctermbg=blue guibg=blue

function! Highlight(text)
    :execute "match blue /" . a:text . "/"
endfunction

:command! -nargs=1 Highlight :call Highlight(<q-args>)
Run Code Online (Sandbox Code Playgroud)

要运行它并突出显示所有出现的正则表达式:

:Highlight foobar
Run Code Online (Sandbox Code Playgroud)

请注意,我尽量不在 .vimrc 中缩写命令/函数。在命令行上输入时保存缩写。