3

What is the recommended way to run VimScript normal commands in Neovim with Lua?

Sometimes, I can achieve things very easily with a few keypresses executed as a normal command compared to scripting the whole thing with Lua API.

Now I know I can use vim.cmd and just put the whole normal ... command inside there, but I was wondering if there was any overhead to this and if yes what is then the best way to do it?

1
  • Do you still have something open in your question? How can we help you further? Commented May 5, 2023 at 10:36

2 Answers 2

2

My understanding is that Lua API is to be an alternative to VimScript API (function calls) but not to replace Vim commands.

Vim commands are and will be available from Lua using the vim.cmd call among others.

The overhead is minimal (the parsing of the Vim command). But if the action is complex, the Vim command is in general more performant than its simulation using the VimScript API or its Lua variant (C code is likely to be more performant than script code).

My recommendation is to use Vim command whenever possible unless it can be replaced by one API call (VimScipt API or ots Lua variant)

Keep VimScipt or its Lua variant for what can't be done with Vim commands.

Here another answer from an expert sharing its opinion.

1
  • 1
    Good answer but source? Commented Jun 2, 2023 at 16:52
4

I believe you can do a bit better than vim.cmd('normal w') using:

 vim.cmd.normal('w')

Unfortunately, keycode are not expanded. You have to combine it with nvim_replace_termcodes():

vim.cmd.normal(vim.api.nvim_replace_termcodes('<Up>', true, true, true))

Note that vim.keymap.set() automatically expand keycodes, so if your idea was to set your keybind using lua, it is still far shorter to use vimscript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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