From f0bf297fae2d6a7c5bd56c3a0f2a06bf8e5f3f22 Mon Sep 17 00:00:00 2001 From: Austen Adler Date: Sat, 3 Sep 2022 02:03:10 -0400 Subject: [PATCH] Add incr/decr --- src/incr.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 5 +++++ 2 files changed, 49 insertions(+) create mode 100644 src/incr.rs diff --git a/src/incr.rs b/src/incr.rs new file mode 100644 index 0000000..1dcd075 --- /dev/null +++ b/src/incr.rs @@ -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 { + 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, + ) + }) +} diff --git a/src/main.rs b/src/main.rs index 842f824..38953c6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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 { // 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), } }