til / neovim key map helper in lua
When I migrated my dotfiles to Lua, I found myself repeating some patterns, such as adding key mappings, in multiple files. To learn more about Lua, I decided to create a utility module to simplify this handling.
1-- utils.lua
2local M = {}
3
4return M
We start by creating a utils.lua
file in our lua
folder and add a local variable called M
. We set it to an empty table and return it at the end of the file. This setup and naming is a common convention in Lua modules.
1-- utils.lua
2local M = {}
3
4function M.map(lhs, rhs, mode, opts)
5 local options = { noremap = true, silent = true }
6 mode = mode or "n"
7
8 if opts then
9 options = vim.tbl_extend("force", options, opts)
10 end
11
12 vim.keymap.set(mode, lhs, rhs, options)
13end
14
15return M
We create a map
function on our modules table. Inside, we set up some default options, but we also add the ability to extend/override these options whenever we need to. We also set the default mode to "n"
(normal) as that is the most common use case (at least for me). Lastly, we call vim’s API for creating a key map (see :h vim.keymap.set()
for more information).
This now means we can simplify our key mappings across our Lua files.
1-- Before
2local options = {
3 noremap = true,
4 silent = true,
5}
6
7vim.keymap.set("n", "<C-J>", "<C-W><C-J>", options)
8vim.keymap.set("n", "<C-K>", "<C-W><C-K>", options)
9
10-- After
11-- Importing paths start from the `lua` folder
12local map = require("utils").map
13
14map("<C-J>", "<C-W><C-J>")
15map("<C-K>", "<C-W><C-K>")