35 lines
1.1 KiB
Rust
Raw Normal View History

use evalexpr::{eval, Value};
2022-07-15 18:50:40 -04:00
use kakplugin::{get_selections, open_command_fifo, set_selections, KakError, Selection};
2022-10-02 09:57:37 -04:00
use std::{borrow::Cow, io::Write};
#[derive(clap::StructOpt, Debug)]
pub struct Options;
2022-06-05 00:59:05 -04:00
pub fn math_eval(_options: &Options) -> Result<String, KakError> {
let mut err_count: usize = 0;
let selections = get_selections(None)?;
2022-07-15 18:50:40 -04:00
set_selections(selections.iter().map(|s| match eval(s) {
2022-10-02 09:57:37 -04:00
Ok(Value::Float(f)) => Cow::Owned(f.to_string()),
Ok(Value::Int(f)) => Cow::Owned(f.to_string()),
Ok(_) => Cow::Borrowed(""),
2022-07-15 18:50:40 -04:00
Err(e) => {
eprintln!("Error: {:?}", e);
err_count = err_count.saturating_add(1);
// Set the selection to empty
2022-10-02 09:57:37 -04:00
Cow::Borrowed("")
}
2022-07-15 18:50:40 -04:00
}))?;
2022-07-15 18:50:40 -04:00
Ok(if err_count == 0 {
format!("Processed {} selections", selections.len())
} else {
format!(
2022-09-06 00:28:00 -04:00
"Processed {} selections ({} error{})",
2022-07-15 18:50:40 -04:00
selections.len().saturating_sub(err_count),
2022-09-06 00:28:00 -04:00
err_count,
if err_count == 1 { "" } else { "s" }
2022-07-15 18:50:40 -04:00
)
})
}