From bcd5ee2e604976189c11a5b82a4cdd34626a8f75 Mon Sep 17 00:00:00 2001 From: Austen Adler Date: Wed, 30 Oct 2024 20:53:57 -0400 Subject: [PATCH] Allow calculator to be customized as a parameter --- src/math_eval.rs | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/src/math_eval.rs b/src/math_eval.rs index b45311d..eedbaff 100644 --- a/src/math_eval.rs +++ b/src/math_eval.rs @@ -3,21 +3,34 @@ use kakplugin::{get_selections, set_selections, KakError}; use std::borrow::Cow; #[derive(clap::Args, Debug)] -pub struct Options; -pub fn math_eval(_options: &Options) -> Result { +pub struct Options { + /// 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>, +} +pub fn math_eval(options: &Options) -> Result { let mut err_count: usize = 0; let selections = get_selections(None)?; - set_selections(selections.iter().map(|s| match eval(s) { - 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("") + let extra = options.extra_math_args.as_ref().map(|v| v.join(" ")); + + set_selections(selections.iter().map(|s| { + match eval(&if let Some(e) = &extra { + Cow::Owned(format!("{s} {e}")) + } else { + Cow::Borrowed(s) + }) { + 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("") + } } }))?;