I know I can get the current mode, via mode(), but is it possible to set the current mode from viml or preferably lua (though I know a vim command/fn can be gotten to via the lua bridge).

I know I can (nvim_)feedkeys(<mode>), but it feels like it's kind of a backwards way, faking input to alter state. :insert is for inserting lines, :normal runs commands in normal mode, but doesn't actually change the editor mode.

Is there really no win_set_mode('n') or similar? feedkeys is the correct method?

Edit per comment:

Specifically right now, today, this moment, I want to call nvim_set_current_window(win_nr) and then enter insert or normal mode in that window depending on other contexts.

I can do:

local keys = vim.api.nvim_replace_termcodes("<ESC>", true, false, true)
vim.api.nvim_feedkeys(keys, "i", true)

but I'd much rather:

vim.api.nvim_set_mode('i') -- or vim.fn.some_vim_mode_fn('i')

if it exists.

But I've had the same class of issue when writing vimscript and wanting to toggle mode.

  • 1
    Sounds like XY problem to me. If you run VimL you've already got into that mode somehow. It would be better if you explain what's you real point. – Matt Oct 25 '20 at 12:14
  • See edit. (character length requirement.) – markson edwardson Oct 25 '20 at 12:43
  • Not if you switch to the window while in insert mode (via imap ... <Cmd>...) since <Cmd> can run without changing the mode of whatever context it's running in. I could put <esc> in the imap but I wanted to know if the described functionality existed. :startinsert/:stopinsert/vim.cmd('startinsert') is probably as close as it gets if you want to put it as an answer.. – markson edwardson Oct 25 '20 at 13:05
  • PS Welcome to Vi and Vim! – D. Ben Knoble Oct 25 '20 at 17:11
  • It looks like some mode changes are easier than others. startinsert is also mentioned here but a command to change to other modes appears to not exist. – joeytwiddle Oct 26 '20 at 10:56

After some conversation with the OP, we settled on

:startinsert/:stopinsert/vim.cmd('startinsert') is probably as close as it gets

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.