nvrim/plugins/
fkr.rs

1//! Random string generation helpers backed by [`fkr`].
2//!
3//! Exposes a dictionary with an insertion command (`insert_string`) prompting the user to select an
4//! [`::fkr::FkrOption`] then inserting the generated string at the cursor. Input / buffer errors are
5//! reported via [`ytil_noxi::notify::error`].
6
7use fkr::FkrOption;
8use nvim_oxi::Dictionary;
9use nvim_oxi::api::Buffer;
10use strum::IntoEnumIterator;
11use ytil_noxi::buffer::BufferExt as _;
12
13/// [`Dictionary`] of random string generation helpers powered by [`fkr`].
14///
15/// Entries:
16/// - `"insert_string"` inserts a generated value at the current cursor position replacing any active selection via the
17///   buffer helper.
18pub fn dict() -> Dictionary {
19    dict! {
20        "insert_string": fn_from!(insert_string),
21    }
22}
23
24/// Prompt the user to select a [`fkr::FkrOption`] and insert its generated string.
25///
26/// The user is shown a selection menu via [`ytil_noxi::vim_ui_select::open`]; on
27/// selection the corresponding generated string is inserted at the cursor using
28/// [`ytil_noxi::buffer::BufferExt::set_text_at_cursor_pos`].
29///
30/// Behaviour:
31/// - Returns early (no insertion) if fetching user input fails or is canceled.
32/// - Emits error notifications to Nvim for selection prompt or buffer write failures.
33fn insert_string(_: ()) {
34    let opts: Vec<FkrOption> = FkrOption::iter().collect();
35
36    let callback = {
37        let opts = opts.clone();
38        move |choice_idx| {
39            let selected_opt: Option<&FkrOption> = opts.get(choice_idx);
40            if let Some(selected_opt) = selected_opt {
41                Buffer::current().set_text_at_cursor_pos(&selected_opt.gen_string());
42            }
43        }
44    };
45
46    if let Err(err) = ytil_noxi::vim_ui_select::open(opts, &[("prompt", "Select option: ")], callback, None) {
47        ytil_noxi::notify::error(format!("error generating fkr value | error={err:#?}"));
48    }
49}