Skip to content

Instantly share code, notes, and snippets.

@cipharius
Last active April 18, 2024 14:39
Show Gist options
  • Save cipharius/6f5132bfbd447c1e89c33ab9583657ee to your computer and use it in GitHub Desktop.
Save cipharius/6f5132bfbd447c1e89c33ab9583657ee to your computer and use it in GitHub Desktop.
Sort kakoune selections using GNU sort utility
define-command sort-selections -params 0.. -override -docstring '
sort-selections: Sort current selections using GNU sort utility
All parameters will be passed to the GNU sort utility
' %{
# Copy current selections to a temporary sort buffer
execute-keys %{"sy}
edit -scratch *sort-selections*
execute-keys %{"s<a-p>}
# Seperate selections with null characters
execute-keys %{<a-!>printf '\000'<ret>ggd}
# Sort the buffer
# Use `head -c-1` to get rid of leading newline
execute-keys "%%|head -c-1|sort -z %arg{@}<ret>"
# Yank the sorted candidates
execute-keys %{%HS\x00<ret>"sy}
# Update the original buffer
delete-buffer
execute-keys %{"sR}
}
@JJK96
Copy link

JJK96 commented Jul 19, 2019

How about this generalized version?

define-command pipe-selections -params 1.. -override -docstring '
sort-selections: Pipe all selections newline delimited through a shell command and return the result in place.
' %{
    # Copy current selections to a temporary sort buffer
    execute-keys %{"sy}
    edit -scratch *pipe-selections*
    execute-keys %{"s<a-P>a<ret><esc>gjd}

    # Sort the buffer
    execute-keys "%%|%arg{@}<ret>"

    # Yank the sorted candidates
    execute-keys %{%<a-s>H"sy}

    # Update the original buffer
    delete-buffer
    execute-keys %{"sR}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment