diff --git a/src/main.rs b/src/main.rs index 7b54da5..36901a0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,6 +14,7 @@ mod kak; mod math_eval; mod shuf; mod sort; +mod trim; mod uniq; use clap::{Parser, Subcommand}; use errors::KakMessage; @@ -39,6 +40,7 @@ enum Commands { Uniq(uniq::Options), #[clap(visible_aliases = &["bc", "eval"])] MathEval(math_eval::Options), + Trim(trim::Options), } fn main() { @@ -73,6 +75,7 @@ fn run() -> Result { Commands::Shuf(o) => shuf::shuf(o), Commands::Uniq(o) => uniq::uniq(o), Commands::MathEval(o) => math_eval::math_eval(o), + Commands::Trim(o) => trim::trim(o), } } diff --git a/src/trim.rs b/src/trim.rs new file mode 100644 index 0000000..75f6d21 --- /dev/null +++ b/src/trim.rs @@ -0,0 +1,55 @@ +use crate::{get_selections, open_command_fifo, KakMessage}; +use std::io::Write; + +#[derive(clap::StructOpt, Debug)] +pub struct Options { + #[clap(short, long)] + left: bool, + #[clap(short, long)] + right: bool, + #[clap(short, long)] + no_preserve_newline: bool, +} + +pub fn trim(options: &Options) -> Result { + let selections = get_selections()?; + + let mut f = open_command_fifo()?; + write!(f, "reg '\"'")?; + + let mut num_trimmed: usize = 0; + let num_selections = selections.len(); + + for i in selections.into_iter().map(|s| { + let new_string = match (options.left, options.right) { + (true, true) | (false, false) => { + // Either they specified both, or neither + s.trim() + } + (true, false) => s.trim_start(), + (false, true) => s.trim_end(), + }; + + if s.len() != new_string.len() { + num_trimmed = num_trimmed.saturating_add(1); + } + + if !options.no_preserve_newline && s.ends_with('\n') { + s + "\n" + } else { + new_string.to_string() + } + }) { + write!(f, " '{}'", i.replace('\'', "''"))?; + } + write!(f, " ; exec R;")?; + f.flush()?; + + Ok(KakMessage( + format!( + "Trimmed {} selections ({} changed)", + num_selections, num_trimmed + ), + None, + )) +}