A concrete Python 'Hello World' with the Neovim API

Dec 27, 2021 21:20 · 207 words · 1 minute read neovim python

Neovim’s API is typically called through a Remote Procedure Call (RPC) using the MessagePack-RPC specification. The neovim documentation provides a ‘Hello World’ example of how to interface with the Neovim API; this post is a worked example of how to implement this - more of a note to self than anything else. I’m running Neovim v 0.6.0 on Manjaro 21.2.0 Qonos linux.

First we need to determine the servername that Neovim has set on startup. Fire up an instance of nvim from the terminal with the command:

nvim -c "echo v:servername"

The -c command option used above causes neovim to run a command on opening, in this case to print out the servername of the instance. Resultantly we should see the servername of the instance in the statusline; it should look a little like: /tmp/nvimt7lIuM/0.

We can now use this address to command the neovim instance remotely. Create a file named nvim-hw-api.py and paste the following - altering the path to match the servername we found above:

from pynvim import attach
nvim = attach('socket', path='/tmp/nvimt7lIuM/0')
nvim.command('echo "hello world!"')

At the terminal run (assuming Python3 is installed):

python3 nvim-hw-api.py

And if all works as forecast we should see hello world! appear in the statusline of the neovim instance!

tweet Buy Me a Coffee at ko-fi.com
₿⚡ Or buy me a coffee with Bitcoin Lightning