ytil_noxi/
common.rs

1//! Common utilities for Nvim API interactions, including variable setting and command execution.
2
3use core::fmt::Debug;
4
5use nvim_oxi::api::opts::CmdOpts;
6use nvim_oxi::api::opts::ExecOpts;
7use nvim_oxi::api::types::CmdInfosBuilder;
8use nvim_oxi::conversion::ToObject;
9
10/// Sets the value of a global Nvim variable `name` to `value`.
11///
12/// Wraps [`nvim_oxi::api::set_var`].
13///
14/// Errors are reported to Nvim via [`crate::notify::error`].
15pub fn set_g_var<V: ToObject + Debug>(name: &str, value: V) {
16    let msg = format!("error setting global var | name={name} value={value:#?}");
17    if let Err(err) = nvim_oxi::api::set_var(name, value) {
18        crate::notify::error(format!("{msg} | error={err:#?}"));
19    }
20}
21
22/// Execute an ex command with optional arguments.
23///
24/// Wraps [`nvim_oxi::api::cmd`], reporting failures through [`crate::notify::error`].
25///
26/// # Errors
27/// Errors from [`nvim_oxi::api::cmd`] are propagated after logging via [`crate::notify::error`].
28pub fn exec_vim_cmd(
29    cmd: impl AsRef<str> + Debug + std::marker::Copy,
30    args: Option<&[impl AsRef<str> + Debug]>,
31) -> Result<Option<String>, nvim_oxi::api::Error> {
32    let mut cmd_infos_builder = CmdInfosBuilder::default();
33    cmd_infos_builder.cmd(cmd.as_ref());
34
35    if let Some(args) = args {
36        cmd_infos_builder.args(args.iter().map(|s| s.as_ref().to_string()));
37    }
38    nvim_oxi::api::cmd(&cmd_infos_builder.build(), &CmdOpts::default()).inspect_err(|err| {
39        crate::notify::error(format!(
40            "error executing cmd | cmd={cmd:?} args={args:#?} error={err:#?}",
41        ));
42    })
43}
44
45/// Executes Vimscript source code and returns the output if any.
46///
47/// # Errors
48/// Errors are reported to Nvim via [`crate::notify::error`].
49#[allow(clippy::option_option)]
50pub fn exec_vim_script(src: &str, opts: Option<ExecOpts>) -> Option<Option<String>> {
51    let opts = opts.unwrap_or_default();
52    Some(
53        nvim_oxi::api::exec2(src, &opts)
54            .inspect_err(|err| {
55                crate::notify::error(format!(
56                    "error executing Vimscript | src={src:?} opts={opts:?} error={err:?}"
57                ));
58            })
59            .ok()?
60            .map(|s| s.to_string()),
61    )
62}