Allow calculator to be customized as a parameter

This commit is contained in:
Austen Adler 2024-10-30 20:53:57 -04:00
parent cf5bf59333
commit bcd5ee2e60

View File

@ -3,21 +3,34 @@ use kakplugin::{get_selections, set_selections, KakError};
use std::borrow::Cow; use std::borrow::Cow;
#[derive(clap::Args, Debug)] #[derive(clap::Args, Debug)]
pub struct Options; pub struct Options {
pub fn math_eval(_options: &Options) -> Result<String, KakError> { /// Additional arguments to pass to the math evaluator
///
/// For example, you can run `kakutils-rs bc + 5` to add 5 to all selections
extra_math_args: Option<Vec<String>>,
}
pub fn math_eval(options: &Options) -> Result<String, KakError> {
let mut err_count: usize = 0; let mut err_count: usize = 0;
let selections = get_selections(None)?; let selections = get_selections(None)?;
set_selections(selections.iter().map(|s| match eval(s) { let extra = options.extra_math_args.as_ref().map(|v| v.join(" "));
Ok(Value::Float(f)) => Cow::Owned(f.to_string()),
Ok(Value::Int(f)) => Cow::Owned(f.to_string()), set_selections(selections.iter().map(|s| {
Ok(_) => Cow::Borrowed(""), match eval(&if let Some(e) = &extra {
Err(e) => { Cow::Owned(format!("{s} {e}"))
eprintln!("Error: {:?}", e); } else {
err_count = err_count.saturating_add(1); Cow::Borrowed(s)
// Set the selection to empty }) {
Cow::Borrowed("") Ok(Value::Float(f)) => Cow::Owned(f.to_string()),
Ok(Value::Int(f)) => Cow::Owned(f.to_string()),
Ok(_) => Cow::Borrowed(""),
Err(e) => {
eprintln!("Error: {:?}", e);
err_count = err_count.saturating_add(1);
// Set the selection to empty
Cow::Borrowed("")
}
} }
}))?; }))?;