Home Writing Reading

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.

-- utils.lua
local M = {}

return 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.

-- utils.lua
local M = {}

function M.map(lhs, rhs, mode, opts)
	local options = { noremap = true, silent = true }
	mode = mode or "n"

	if opts then
		options = vim.tbl_extend("force", options, opts)
	end

	vim.keymap.set(mode, lhs, rhs, options)
end

return 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.

-- Before
local options = {
	noremap = true,
	silent = true,
}

vim.keymap.set("n", "<C-J>", "<C-W><C-J>", options)
vim.keymap.set("n", "<C-K>", "<C-W><C-K>", options)

-- After
-- Importing paths start from the `lua` folder
local map = require("utils").map

map("<C-J>", "<C-W><C-J>")
map("<C-K>", "<C-W><C-K>")

  • Loading next post...
  • Loading previous post...