Checking whether a count was given (comparing %val{count} to zero)

When defining a mapping, you can check whether a count was given using the following trick:

try %{
    execute-keys -draft "%val{count}s.<ret>"
    echo "No count given"
} catch %{
    echo "Count is %val{count}"

This allows the mapping to behave differently depending on whether a count was given or not (the same way g in normal mode behaves differently when a count is given).

When no count is given, %val{count} is 0 which does nothing in execute-keys, and execute-keys succeeds.
When a count is positive, execute-keys fails with “invalid capture number”.


This is actually inefficient with large selections, because Kakoune will temporarily create a new selection for each character. It’s better to shrink the selections first:

execute-keys -draft "<space>;%val{count}s.<ret>"