rust-selection-sort.kak/src/trim.rs

54 lines
1.4 KiB
Rust
Raw Normal View History

2022-06-05 00:59:05 -04:00
use kakplugin::{get_selections, open_command_fifo, KakError};
2022-04-02 19:27:30 -04:00
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,
}
2022-06-05 00:59:05 -04:00
pub fn trim(options: &Options) -> Result<String, KakError> {
2022-04-02 19:27:30 -04:00
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') {
2022-06-09 18:11:11 -04:00
eprintln!("Adding newline: {s:?}");
new_string.to_owned() + "\n"
2022-04-02 19:27:30 -04:00
} else {
2022-06-09 18:11:11 -04:00
new_string.to_owned()
2022-04-02 19:27:30 -04:00
}
}) {
write!(f, " '{}'", i.replace('\'', "''"))?;
}
write!(f, " ; exec R;")?;
f.flush()?;
2022-06-05 00:59:05 -04:00
Ok(format!(
"Trimmed {} selections ({} changed)",
num_selections, num_trimmed
2022-04-02 19:27:30 -04:00
))
}