Skip to content

Commit

Permalink
Add selection::sort_lines command
Browse files Browse the repository at this point in the history
Signed-off-by: Christoph Heiss <christoph@c8h4.io>
  • Loading branch information
christoph-heiss committed Sep 27, 2024
1 parent dae913c commit 85cc416
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/commands/selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,44 @@ fn sel_to_range(app: &mut Application) -> std::result::Result<Range, Error> {
}
}

pub fn sort_lines(app: &mut Application) -> Result {
let buffer = app
.workspace
.current_buffer
.as_mut()
.ok_or(BUFFER_MISSING)?;

let line_range = match app.mode {
Mode::SelectLine(ref mode) => {
util::inclusive_range(&LineRange::new(mode.anchor, buffer.cursor.line), buffer)
}
_ => bail!("Can't sort lines outside of select line mode"),
};

let lines = buffer
.read(&line_range)
.ok_or("Couldn't read lines to sort from buffer")?;

let had_newline_at_end = lines.ends_with('\n');

let mut lines: Vec<&str> = lines.split_terminator('\n').collect();

lines.sort();
let mut lines = lines.join("\n");

if had_newline_at_end {
lines.push('\n'); // Add final newline again
}

buffer.start_operation_group();
buffer.delete_range(line_range.clone());
buffer.cursor.move_to(line_range.start());
buffer.insert(lines);
buffer.end_operation_group();

application::switch_to_normal_mode(app)
}

#[cfg(test)]
mod tests {
use crate::commands;
Expand Down
1 change: 1 addition & 0 deletions src/input/key_map/default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ select_line:
- view::scroll_to_cursor
c: selection::change
y: selection::copy
o: selection::sort_lines
p:
- buffer::paste
- application::switch_to_normal_mode
Expand Down

0 comments on commit 85cc416

Please sign in to comment.