I’m certain we’re all familiar with the following pattern:
define-command foobar-enable %{
echo enabling foobar...
# ...
}
define-command foobar-disable %{
echo disabling foobar...
# ...
}
Fair enough, it’s simple, and a lot of plugins follow this convention. However, what if we want a simple way to toggle between the two states with a simple command? For example, I’m a big fan of having various toggles in a user mode.
declare-option bool foobar_toggle_state false
define-command foobar-toggle %{
eval %sh{
if [ "$kak_opt_foobar_toggle_state" = true ]; then
echo "foobar-disable"
echo "set window foobar_toggle_state false"
else
echo "foobar-enable"
echo "set window foobar_toggle_state true"
fi
}
}
All of a sudden, it’s a lot more complicated. Setting up multiple toggles this way can get out of hand and spaghettify your config really fast. So I wrote a plugin that basically automates this. Meet kak-toggle. I’ll share an example, creating a toggle for the “wrap” highlighter.
register-toggle toggle-wrap false %{
# This block is evaluated when toggle is turned on
add-highlighter "%arg{1}/wrap" wrap -word -indent
echo "Wrap enabled!"
} %{
# This block is evaluated when toggle is turned of
remove-highlighter "%arg{1}/wrap"
echo "Wrap disabled!"
}
What this does is define a command called toggle-wrap, and it takes care of all the state options and whatnot behind the scenes. You can call the toggle-wrap command to, well, toggle it! The first block of commands is ran when the toggle is turned on, and the second runs when the toggle is turned off. The false in the definition is just setting the initial state of the boolean.
The scope is also given as a parameter to the enabling & disabling commands, meaning you can reference it as %arg{1} and make your toggle more dynamic by supporting multiple scopes. And finally, you can optionally “ensure” a state instead of just toggling. For example, imagine you want wrap to always be enabled on certain filetypes:
hook global WinSetOption filetype=markdown %{
toggle-wrap window true
}
Hopefully some of you find this helpful!