How to get text in current buffer in neovim using Python API?

Viewed 289

I want to make a plugin for neovim using the Python API (pynvim). The problem is I want to get the current buffer's text, updated real time. I have searched on the web and didnt find any useful (or understandable) documentation for this.

1 Answers

You can use pynvim to subscribe to an event in neovim. Do keep in mind that pynvim is async, but my example is using a simple while loop do demonstrate how to monitor for realtime change in a buffer and get its content.

from time import sleep
from pynvim import attach, api

nvim = attach('socket', path='/tmp/nvim')

buffer = nvim.current.buffer

event = api.nvim.Nvim.from_nvim(nvim) # use the loaded nvim session
listen = event.subscribe('TextChangedI') # refer to events https://neovim.io/doc/user/autocmd.html#events

while True:
    sleep(2)
    print(listen)
    # read and print contents of the whole buffer
    for line in range(len(buffer)):
        print(buffer[line])
Related