Restoring initial selections after an error in kakscript

I seem to be missing something about the scope of registers, or how the default mark register (^) works.

Attempting to save and then restore initial selections in the event of an error behaves as though the initial selection save was ignored:

define-command restore-selections-tests %{
    execute-keys Z     # save initial selection
    try %{
        select 2.1,2.3 # change selection
        fail           # simulate error; execute catch
    } catch %{
        execute-keys z # restore initial selection <- behaves as if the first Z command never happened
    }
}

Can anyone explain why this is, and how one might solve this problem?

By default, execute-keys restores the register ^ which stores the zZ selections. To turn this off use the -save-regs switch:

define-command restore-selections-tests %{
    execute-keys -save-regs '' Z     # save initial selection
    try %{
        select 2.1,2.3 # change selection
        fail           # simulate error; execute catch
    } catch %{
        execute-keys z # restore initial selection <- behaves as if the first Z command never happened
    }
}

Perfect, thanks!

Now that I know where to look, I see this is indeed in the execeval docs:

execute-keys also save the following registers, who are then restored when the commands have been executed: /, ", |, ^, @.

Also note that the user might have their own particular set of selections stored in "^. Unless your command is specifically for saving a set of selections to "^, the idiomatic thing to do would be to wrap your command body in evaluate-commands -save-regs ^ %{}so that Kakoune always saves and restores the register itself, without you having to do anything.