2022-03-06 21:28:16 -05:00
|
|
|
use evalexpr::{eval, Value};
|
2022-06-05 00:59:05 -04:00
|
|
|
use kakplugin::{get_selections, open_command_fifo, KakError};
|
2022-03-06 21:28:16 -05:00
|
|
|
use std::io::Write;
|
|
|
|
|
2022-07-06 21:14:09 -04:00
|
|
|
// TODO: Context for log() and others
|
|
|
|
|
2022-03-06 21:28:16 -05:00
|
|
|
#[derive(clap::StructOpt, Debug)]
|
|
|
|
pub struct Options;
|
2022-06-05 00:59:05 -04:00
|
|
|
pub fn math_eval(_options: &Options) -> Result<String, KakError> {
|
2022-03-09 20:30:41 -05:00
|
|
|
let selections = get_selections()?;
|
2022-03-06 21:28:16 -05:00
|
|
|
|
|
|
|
let mut f = open_command_fifo()?;
|
|
|
|
write!(f, "reg '\"'")?;
|
|
|
|
|
|
|
|
let mut err = None;
|
|
|
|
let mut err_count: usize = 0;
|
|
|
|
|
|
|
|
for i in selections.iter().map(|s| {
|
|
|
|
// TODO: Do all of these need to be strings?
|
|
|
|
match eval(s) {
|
|
|
|
Ok(Value::Float(f)) => Some(f.to_string()),
|
|
|
|
Ok(Value::Int(f)) => Some(f.to_string()),
|
|
|
|
// TODO: Should this be none?
|
|
|
|
Ok(_) => None,
|
|
|
|
Err(e) => {
|
|
|
|
eprintln!("Error: {:?}", e);
|
|
|
|
if err.is_none() {
|
|
|
|
err = Some(e);
|
|
|
|
err_count = err_count.saturating_add(1);
|
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}) {
|
|
|
|
// TODO: String allocation?
|
|
|
|
let new_selection = i.map(|s| s.replace('\'', "''"));
|
|
|
|
// .unwrap_or_else(|| "".to_string());
|
|
|
|
write!(f, " '{}'", new_selection.as_deref().unwrap_or(""))?;
|
|
|
|
}
|
|
|
|
write!(f, " ; exec R;")?;
|
2022-03-07 21:54:10 -05:00
|
|
|
f.flush()?;
|
2022-03-06 21:28:16 -05:00
|
|
|
|
2022-06-05 00:59:05 -04:00
|
|
|
Ok(format!("MathEval {} selections", selections.len()))
|
2022-03-06 21:28:16 -05:00
|
|
|
}
|