Skip to main content

ytil_noxi/
notify.rs

1//! Notification utilities for sending error and warning messages to Nvim.
2
3use std::fmt::Debug;
4
5pub use nvim_oxi::api::opts;
6use nvim_oxi::api::opts::EchoOpts;
7pub use nvim_oxi::api::types;
8
9/// Types that can be converted to a notification message for Nvim.
10///
11/// Implementors provide a way to transform themselves into a string suitable for display
12/// in Nvim notifications.
13pub trait Notifiable: Debug {
14    fn to_msg(&self) -> impl AsRef<str>;
15}
16
17impl<T: Notifiable + ?Sized> Notifiable for &T {
18    fn to_msg(&self) -> impl AsRef<str> {
19        (*self).to_msg()
20    }
21}
22
23impl Notifiable for rootcause::Report {
24    fn to_msg(&self) -> impl AsRef<str> {
25        self.to_string()
26    }
27}
28
29impl Notifiable for String {
30    fn to_msg(&self) -> impl AsRef<str> {
31        self
32    }
33}
34
35impl Notifiable for &str {
36    fn to_msg(&self) -> impl AsRef<str> {
37        self
38    }
39}
40
41/// Notifies the user of an error message in Nvim.
42pub fn error<N: Notifiable>(notifiable: N) {
43    if let Err(err) = echo(notifiable.to_msg().as_ref(), "ErrorMsg") {
44        nvim_oxi::dbg!(format!("cannot notify error | msg={notifiable:?} error={err:#?}"));
45    }
46}
47
48/// Notifies the user of a warning message in Nvim.
49pub fn warn<N: Notifiable>(notifiable: N) {
50    if let Err(err) = echo(notifiable.to_msg().as_ref(), "WarningMsg") {
51        nvim_oxi::dbg!(format!("cannot notify warning | msg={notifiable:?} error={err:#?}"));
52    }
53}
54
55fn echo(msg: &str, highlight: &str) -> Result<(), nvim_oxi::api::Error> {
56    nvim_oxi::api::echo([(msg, Some(highlight))], true, &EchoOpts::default()).map(drop)
57}