5

I'm a little confused. Is vim.cmd just a shorthand for vim.api.nvim_command or are they used for different things?

2 Answers 2

10

vim.cmd(command) calls either of these two lua APIs:

  • vim.api.nvim_cmd: when command is a table
  • vim.api.nvim_exec: when command is a string

The lua code for vim.cmd:

vim.cmd = setmetatable({}, {
  __call = function(_, command)
    if type(command) == 'table' then
      return vim.api.nvim_cmd(command, {})
    else
      return vim.api.nvim_exec(command, false)
    end
  end,
  -- CODE TRUNCATED
  -- not necessary for this SO answer
  -- visit full source code on github
  -- https://github.com/neovim/neovim/blob/afb7efb3733962649f3c0897a25dc5fff60a66c6/runtime/lua/vim/_editor.lua#L335-L368
})

Both of these APIs differ slightly from vim.api.nvim_command. When to use which is laid out in :h nvim_command:

nvim_command({command})                                       *nvim_command()*
    Executes an Ex command.

    On execution error: fails with VimL error, updates v:errmsg.

    Prefer using |nvim_cmd()| or |nvim_exec()| over this. To evaluate multiple
    lines of Vim script or an Ex command directly, use |nvim_exec()|. To
    construct an Ex command using a structured format and then execute it, use
    |nvim_cmd()|. To modify an Ex command before evaluating it, use
    |nvim_parse_cmd()| in conjunction with |nvim_cmd()|.
3
  • Glad you are also addressing vim.api.nvim_command, since it has nothing to do with vim.cmd. Given the vim.api.nvim_command help: When should I even use nvim_command over cmd (vim.api.nvim_cmd, vim.api.nvim_exec)? Commented Sep 30, 2022 at 19:14
  • @MartinBraun, probably never. It's a simple api function that only calls the C function for ex commands. It's an old api (from api level 1); and I'm guessing it's functionally deprecated/superseded by the other two more robust apis (nvim_exec from lvl 7 and nvim_cmd from lvl 10).
    – 3N4N
    Commented Sep 30, 2022 at 20:22
  • @MartinBraun here are source codes for the three APIs: 1) nvim_command, 2) nvim_cmd, and 3) nvim_exec. Notice that the latter two apis are significantly more intricate. Also notice their FUNC_API_SINCE value, which signifies how old they are.
    – 3N4N
    Commented Sep 30, 2022 at 20:27
2

vim.cmd(·) is the same as vim.api.nvim_exec(·, false) when passed a string. However, when passed a table, it behaves like vim.api.nvim_cmd(·, {})

vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true }

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.