Skip to content

Commit

Permalink
add trim command
Browse files Browse the repository at this point in the history
  • Loading branch information
kirawi committed Sep 4, 2022
1 parent c93d52c commit 44e5a40
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
1 change: 1 addition & 0 deletions book/src/generated/typable-cmd.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,4 @@
| `:append-output` | Run shell command, appending output after each selection. |
| `:pipe` | Pipe each selection to the shell command. |
| `:run-shell-command`, `:sh` | Run a shell command |
| `:trim` | Trim trailing whitespace. Args: 'all' (default), 'spaces', 'lines' |
65 changes: 65 additions & 0 deletions helix-term/src/commands/typed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1515,6 +1515,64 @@ fn run_shell_command(
Ok(())
}

fn trim(cx: &mut compositor::Context, args: &[Cow<str>], event: PromptEvent) -> anyhow::Result<()> {
if event != PromptEvent::Validate {
return Ok(());
}

use helix_core::line_ending;

// Possible modes: "all", "spaces", "lines".
let mode = args.get(0).unwrap_or(&Cow::Borrowed("all"));
let (view, doc) = current!(cx.editor);

if mode == "all" || mode == "spaces" {
let mut pos = 0;
let transaction = Transaction::change(
doc.text(),
doc.text().lines().filter_map(|line| {
// The index of the last non-whitespace character in the line.
let start = pos
+ movement::backwards_skip_while(
line,
line_ending::rope_end_without_line_ending(&line),
|x| x.is_whitespace(),
)
.unwrap_or(0);

// The index of the last character in the line, excluding the line ending.
let end = pos + line_ending::rope_end_without_line_ending(&line);
pos += line.len_chars();
(start != end).then(|| (start, end, None))
}),
);
doc.apply(&transaction, view.id);
}

if mode == "all" || mode == "lines" {
let mut lines = doc.text().lines_at(doc.text().len_lines()).reversed();
let mut pos = doc.text().len_chars();

// The last non-empty line char index.
let start = lines
.find_map(|line| {
if line_ending::rope_end_without_line_ending(&line) != 0 {
Some(pos)
} else {
pos -= line.len_chars();
None
}
})
.unwrap_or(0);
let end = doc.text().len_chars();
let transaction = Transaction::change(doc.text(), [(start, end, None)].into_iter());
doc.apply(&transaction, view.id);
}

doc.append_changes_to_history(view.id);
Ok(())
}

pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[
TypableCommand {
name: "quit",
Expand Down Expand Up @@ -1995,6 +2053,13 @@ pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[
fun: run_shell_command,
completer: Some(completers::directory),
},
TypableCommand {
name: "trim",
aliases: &[],
doc: "Trim trailing whitespace. Args: 'all' (default), 'spaces', 'lines'",
fun: trim,
completer: None,
},
];

pub static TYPABLE_COMMAND_MAP: Lazy<HashMap<&'static str, &'static TypableCommand>> =
Expand Down

0 comments on commit 44e5a40

Please sign in to comment.