Allow calculator to be customized as a parameter
This commit is contained in:
parent
cf5bf59333
commit
bcd5ee2e60
@ -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<String, KakError> {
|
||||
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<Vec<String>>,
|
||||
}
|
||||
pub fn math_eval(options: &Options) -> Result<String, KakError> {
|
||||
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("")
|
||||
}
|
||||
}
|
||||
}))?;
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user