mapx.nvim icon indicating copy to clipboard operation
mapx.nvim copied to clipboard

Execute multiple commands using a dictionary

Open mystilleef opened this issue 4 years ago • 4 comments

I'm looking for a quick way to execute vim commands without writing functions, like so.

nnoremap([[keymap]], {Command1, Command2, Command3}, silent)

So if the second function in nnoremap is a table, each command in the table can be called using vim.fn.execute or similar.

Is something like this feasible or available, without using Lua functions?

mystilleef avatar Oct 03 '21 10:10 mystilleef

Hello @mystilleef,

I like this idea. We don’t have anything like this at the moment, but I am open to including such a feature in Mapx.

In the mean time, you could accomplish something similar yourself with a helper function:

local function chain(...)
  return function()
    vim.cmd(table.concat({...}, "\n"))
  end
end

nnoremap([[keymap]], chain("Command1", "Command2", "Command3"), silent)

(Note: I’m writing from my phone so I’ve not been able to test this snippet.)

And yes, it requires bit of Lua, but not as much as it would be otherwise.

A final suggestion: you can often chain Vim commands together with the bar | character, though not all commands support this. Read more here.

b0o avatar Oct 03 '21 13:10 b0o

Thanks for your response. Yeah, I resorted to using a similar function. There are too many quirks when using |. Using cmd or execute is more reliable. I figured accepting a dictionary would be a convenient feature and would fit nicely into the APIs, which also supports using multiple mappings with a dictionary.

mystilleef avatar Oct 03 '21 22:10 mystilleef

I agree, I will add this to the backlog. Thank you for the suggestion!

b0o avatar Oct 03 '21 23:10 b0o

For the benefit of those who want a helper function to accomplish this, you can use the following snippet.

local function cmds(...)
  local _cmds = { ... }
  return function()
    vim.tbl_map(vim.fn.execute, _cmds)
  end
end

Usage

nnoremap([[keymap]], cmds("VimCommand1", "VimCommand2", "VimCommand3"), silent)

mystilleef avatar Oct 04 '21 01:10 mystilleef