navy-nvim-rs 0.0.21

A library for writing neovim rpc clients
//! Some manually implemented API functions
use std::io::{self, Error, ErrorKind};

use rmpv::{Value, ValueRef};
use tokio::io::AsyncWrite;

use crate::{
    error::{NeovimError, TypeError},
    neovim::Neovim,
    rpc::{decode::Decode, payload::ResponsePayload},
    uioptions::UiAttachOptions,
};

impl<W> Neovim<W>
where
    W: AsyncWrite + Send + Unpin + 'static,
{
    /// Register as a remote UI.
    ///
    /// After this method is called, the client will receive redraw notifications.
    pub async fn ui_attach(
        &self,
        width: i64,
        height: i64,
        opts: UiAttachOptions<'_>,
    ) -> io::Result<()> {
        let opts = opts.into_value();
        let args = (width, height, &opts);

        let response = self.request("nvim_ui_attach", args).await?;
        decode_response(&response, "nvim_ui_attach")
    }

    pub async fn get_api_info(&self) -> io::Result<Vec<Value>> {
        let response = self.request("nvim_get_api_info", ()).await?;
        match decode_response::<Value>(&response, "nvim_get_api_info")? {
            Value::Array(values) => Ok(values),
            value => Err(Error::new(
                ErrorKind::InvalidData,
                TypeError::new("nvim_get_api_info", "array", value),
            )),
        }
    }

    pub async fn request_input(&self, keys: &str) -> io::Result<u32> {
        let response = self.request("nvim_input", &ValueRef::from(keys)).await?;
        decode_response(&response, "nvim_input")
    }

    #[inline]
    pub async fn notify_input(&self, keys: &str) -> io::Result<()> {
        self.notify("nvim_input", keys).await
    }

    #[inline]
    pub async fn out_write(&self, str: &str) -> io::Result<()> {
        self.notify("nvim_out_write", str).await
    }

    #[inline]
    pub async fn err_write(&self, str: &str) -> io::Result<()> {
        self.notify("nvim_err_write", str).await
    }

    #[inline]
    pub async fn err_writeln(&self, str: &str) -> io::Result<()> {
        self.notify("nvim_err_writeln", str).await
    }

    #[inline]
    pub async fn ui_set_focus(&self, gained: bool) -> io::Result<()> {
        self.notify("nvim_ui_set_focus", gained).await
    }

    #[inline]
    pub async fn ui_try_resize(&self, width: i64, height: i64) -> io::Result<()> {
        let args = (width, height);
        self.notify("nvim_ui_try_resize", args).await
    }

    pub async fn cmd(&self, cmd: ValueRef<'_>, opts: ValueRef<'_>) -> io::Result<String> {
        let response = self.request("nvim_cmd", (&cmd, &opts)).await?;
        decode_response(&response, "nvim_cmd")
    }
}

#[inline]
fn decode_response<'a, D: Decode<'a>>(
    response: &'a ResponsePayload,
    method: &'static str,
) -> io::Result<D> {
    response
        .decode()?
        .map_err(|error| Error::other(NeovimError::new(method, error)))
}