on master help sign in
feat(commands): sort command (#1288)
a4641a8Matouš Dzivjak
book/src/generated/typable-cmd.md+2
@@ -42,3 +42,5 @@
42| `:tutor` | Open the tutorial. |
42| `:tutor` | Open the tutorial. |
43| `:goto`, `:g` | Go to line number. |
43| `:goto`, `:g` | Go to line number. |
44| `:set-option`, `:set` | Set a config option at runtime |
44| `:set-option`, `:set` | Set a config option at runtime |
45+| `:sort` | Sort ranges in selection. |
46+| `:rsort` | Sort ranges in selection in reverse order. |
helix-term/src/commands.rs+65−1
@@ -2671,6 +2671,56 @@ pub mod cmd {
2671 Ok(())
2671 Ok(())
2672 }
2672 }
2673
2673
2674+ fn sort(
2675+ cx: &mut compositor::Context,
2676+ args: &[Cow<str>],
2677+ _event: PromptEvent,
2678+ ) -> anyhow::Result<()> {
2679+ sort_impl(cx, args, false)
2680+ }
2681+
2682+ fn sort_reverse(
2683+ cx: &mut compositor::Context,
2684+ args: &[Cow<str>],
2685+ _event: PromptEvent,
2686+ ) -> anyhow::Result<()> {
2687+ sort_impl(cx, args, true)
2688+ }
2689+
2690+ fn sort_impl(
2691+ cx: &mut compositor::Context,
2692+ _args: &[Cow<str>],
2693+ reverse: bool,
2694+ ) -> anyhow::Result<()> {
2695+ let (view, doc) = current!(cx.editor);
2696+ let text = doc.text().slice(..);
2697+
2698+ let selection = doc.selection(view.id);
2699+
2700+ let mut fragments: Vec<_> = selection
2701+ .fragments(text)
2702+ .map(|fragment| Tendril::from_slice(&fragment))
2703+ .collect();
2704+
2705+ fragments.sort_by(match reverse {
2706+ true => |a: &Tendril, b: &Tendril| b.cmp(a),
2707+ false => |a: &Tendril, b: &Tendril| a.cmp(b),
2708+ });
2709+
2710+ let transaction = Transaction::change(
2711+ doc.text(),
2712+ selection
2713+ .into_iter()
2714+ .zip(fragments)
2715+ .map(|(s, fragment)| (s.from(), s.to(), Some(fragment))),
2716+ );
2717+
2718+ doc.apply(&transaction, view.id);
2719+ doc.append_changes_to_history(view.id);
2720+
2721+ Ok(())
2722+ }
2723+
2674 pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[
2724 pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[
2675 TypableCommand {
2725 TypableCommand {
2676 name: "quit",
2726 name: "quit",
@@ -2965,7 +3015,21 @@ pub mod cmd {
2965 doc: "Set a config option at runtime",
3015 doc: "Set a config option at runtime",
2966 fun: setting,
3016 fun: setting,
2967 completer: Some(completers::setting),
3017 completer: Some(completers::setting),
2968− }
3018+ },
3019+ TypableCommand {
3020+ name: "sort",
3021+ aliases: &[],
3022+ doc: "Sort ranges in selection.",
3023+ fun: sort,
3024+ completer: None,
3025+ },
3026+ TypableCommand {
3027+ name: "rsort",
3028+ aliases: &[],
3029+ doc: "Sort ranges in selection in reverse order.",
3030+ fun: sort_reverse,
3031+ completer: None,
3032+ },
2969 ];
3033 ];
2970
3034
2971 pub static TYPABLE_COMMAND_MAP: Lazy<HashMap<&'static str, &'static TypableCommand>> =
3035 pub static TYPABLE_COMMAND_MAP: Lazy<HashMap<&'static str, &'static TypableCommand>> =