Skip to main content

write neovim plugin with go

· 2 min read

Neovim uses interprocess communications for stuff like that. You have to implement the neovim remote plugin protocol in go (or use a library, if that exists) and then write a server program that does what you want by communicating with nvim.

Neovim 使用进程间通信来处理类似的事情。 你必须在 go 中实现 neovim 远程插件协议(或使用相关库),然后编写一个服务器程序,通过与 nvim 通信来执行你想要的操作。

目前支持的库有:

下面来看看如何去实现?

package main

import (
"strings"
"github.com/neovim/go-client/nvim/plugin"
)

func hello(args []string) (string, error) {
return "Hello " + strings.Join(args, " "), nil
}

func main() {
plugin.Main(func(p *plugin.Plugin) error {
p.HandleFunction(&plugin.FunctionOptions{Name: "Hello"}, hello)
return nil
})
}
  1. 首先将以上代码进行编译go build -o hello,然后将二进制文件放入$GOPATH/bin目录中
  2. 任意位置编写个vim文件,以test.vim为例:
if exists('g:loaded_hello')
finish
endif
let g:loaded_hello = 1

function! s:Requirehello(host) abort
" 'hello' is the binary created by compiling the program above.
return jobstart(['hello'], {'rpc': v:true})
endfunction

call remote#host#Register('hello', 'x', function('s:Requirehello'))
" The following lines are generated by running the program
" command line flag --manifest hello
call remote#host#RegisterPlugin('hello', '0', [
\ {'type': 'function', 'name': 'Hello', 'sync': 1, 'opts': {}},
\ ])

" vim:ts=4:sw=4:et
  1. init.lua加入这句即可vim.cmd('source ~/some/path/test.vim')
  2. 打开vim使用 :echo Hello('world')

来看看效果: