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), } }