Are there any events similar to InsertEnter
and InsertLeave
that I could use for visual mode?
Looking through the helpfiles, I did not fine any.
If not, how would I be able to detect if Vim enters or leaves Visual mode?
Are there any events similar to InsertEnter
and InsertLeave
that I could use for visual mode?
Looking through the helpfiles, I did not fine any.
If not, how would I be able to detect if Vim enters or leaves Visual mode?
September of last year, a new event was added:
commit f1e8876fa2359b572d262772747405d3616db670 (tag: v8.2.3430)
Author: =?UTF-8?q?Magnus=20Gro=C3=9F?= <[email protected]>
Date: 2021-09-12
patch 8.2.3430: no generic way to trigger an autocommand on mode change
Problem: No generic way to trigger an autocommand on mode change.
Solution: Add the ModeChanged autocommand event. (Magnus Gross, closes #8856)
From :h ModeChanged
:
ModeChanged After changing the mode. The pattern is
matched against `'old_mode:new_mode'`, for
example match against `*:c*` to simulate
|CmdlineEnter|.
The following values of |v:event| are set:
old_mode The mode before it changed.
new_mode The new mode as also returned
by |mode()| called with a
non-zero argument.
So you can use the following event pattern:
augroup VisualEvent
autocmd!
autocmd ModeChanged *:[vV\x16]* :echom 'VisualEnter'
autocmd Modechanged [vV\x16]*:* :echom 'VisualLeave'
augroup END
[vV\x16]
is a regex pattern matching either of v (visual mode), V (line-wise), or ctrl-v (block-wise).
Answer found courtesy of clason.
:messages
to see the messages left with echom.
I went ahead and rewrote 3N4N's answer in Lua in case some Neovim users would like to take advantage of this:
local visual_event_group =
vim.api.nvim_create_augroup("visual_event", { clear = true })
vim.api.nvim_create_autocmd("ModeChanged", {
group = visual_event_group,
pattern = { "*:[vV\x16]*" },
callback = function()
print("VisualEnter")
end,
})
vim.api.nvim_create_autocmd("ModeChanged", {
group = visual_event_group,
pattern = { "[vV\x16]*:*" },
callback = function()
print("VisualLeave")
end,
})