Find out number of selections in kak script?

#1

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?

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

Not sure but there may be a simpler method.

1 Like
#3

what about:

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

Thank you Andrey! That works well.

#5

Clever :+1:

#6

As discussed here https://github.com/mawww/kakoune/pull/2503 , 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.

2 Likes
#7

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.

#8

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.

#9

@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.

#10

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