Find out number of selections in kak script?

Sounds like easy, but I didn’t find it. The closest thing I’ve found is %val{selections}, but it lists contents of each selection. I need to find out number of active selections inside %{}, what is the best way?

%sh{ echo "$(echo $kak_selections_length | tr ' ' '\n' | wc -l)" }

Not sure but there may be a simpler method.

1 Like

what about:

define-command sel-cnt %{ evaluate-commands %sh{
    eval "set -- $kak_selections"
    printf "%s\n" "echo $#"
1 Like

Thank you Andrey! That works well.

Clever :+1:

As discussed here , I reckon this value is a fundamental aspect of kakoune and should be available without relying on a shell context. This will lead to a better customization of the status bar.


Shouldn’t using selections_desc (an unambiguous, colon-separated list of selection coordinates) be more complicated, but more reliable than the methods proposed so far?

colons_total=$(printf '%s' "$kak_selections_desc" | tr -d -c ':' | wc -m)
chunks_total=$((colons_total + 1))

seems to work regardless of whether the selections include newlines (or even quoted colons) or not.

What I proposed is a shell script of course, it should be enclosed in %sh{ }. And it works on my version of kak (an old 2016 version available on Debian stable!), I hope the colon-separated format did not change recently.

@TeddyDD variant is similar, but it involves pypes. My variant uses $# which simply is count of arguments set by set. For extra safety we can use $kak_selections_length in my example, but since scripts rely on set -- $kak_opt_optionname pretty heavy to handle lists I’m sure this will be the most accurate result, because if it’s not many scripts will break too.

It did, lists are now space separated. A 2016 Kakoune is considered a prehistoric one. Many breaking changes happened since.