Add incr/decr

This commit is contained in:
Austen Adler 2022-09-03 02:03:10 -04:00
parent 37a0066acf
commit f0bf297fae
2 changed files with 49 additions and 0 deletions

44
src/incr.rs Normal file
View File

@ -0,0 +1,44 @@
use evalexpr::{eval, Value};
use kakplugin::{get_selections, open_command_fifo, set_selections, KakError, Selection};
use std::io::Write;
#[derive(clap::StructOpt, Debug)]
pub struct Options {
#[clap(index = 1, help = "Amount to increment/decrement", default_value = "1")]
amount: isize,
}
pub fn incr(options: &Options, should_increment: bool) -> Result<String, KakError> {
let mut err_count: usize = 0;
let selections = get_selections(Some("_"))?;
set_selections(selections.iter().map(|s| {
match eval(&format!(
"{s}{}{}",
if should_increment { "+" } else { "-" },
options.amount
)) {
Ok(Value::Float(f)) => f.to_string(),
Ok(Value::Int(f)) => f.to_string(),
Ok(_) => String::from(""),
Err(e) => {
eprintln!("Error: {:?}", e);
err_count = err_count.saturating_add(1);
// Set the selection to empty
String::from("")
}
}
}))?;
Ok(if err_count == 0 {
format!("{} {} selections by {}",if options.should_increment {"Incr"} else {"Decr"}, selections.len(), options.amount)
} else {
format!(
"{} {} selections by {} ({} errors)",if options.should_increment {"Incr"} else {"Decr"},
selections.len().saturating_sub(err_count),
options.amount,
err_count,
)
})
}

View File

@ -12,6 +12,7 @@
mod box_;
mod errors;
mod incr;
mod invert;
mod math_eval;
mod set;
@ -62,6 +63,8 @@ enum Commands {
Stdin(stdin::Options),
#[clap(about = "Make boxes out of selections", visible_aliases = &["square"])]
Box_(box_::Options),
Decr(incr::Options),
Incr(incr::Options),
}
fn main() {
@ -111,5 +114,7 @@ fn run() -> Result<String, KakError> {
// Commands::Xargs(o) => xargs::xargs(o),
Commands::Stdin(o) => stdin::stdin(o),
Commands::Box_(o) => box_::box_(o),
Commands::Incr(o) => incr::incr(o, true),
Commands::Decr(o) => incr::incr(o, false),
}
}