Home Writing

til / organize and document key mappings in neovim

As we build our knowledge of vim and expand our dotfiles, we’ll accumulate key mappings. We might spread them across files, promising to “organize them later”. We might even forget what they were if we don’t use them frequently. Luckily, there’s a plug-in that can help us with both organization and recall, which-key.

Before I migrated, I had the following key mappings for harpoon (using my map helper). We’ll migrate them to which-key.

local mark = require("harpoon.mark")
local ui = require("harpoon.ui")

map("n", "<leader>ha", mark.add_file)
map("n", "<leader>hr", mark.rm_file)
map("n", "<C-e>", ui.toggle_quick_menu)

To kick off, we install which-key and call the setup function.

local wk = require("which-key")

wk.setup()

This is everything we need to hook up default mappings. For instance, if we press g we would see all the mappings that start with a g.

A list of default mappings

Some of these come from plugins.

It’s a good idea to decrease timeoutlen from the default 1000 ms so you don’t have to wait too long for the interface to pop up. I’ve got it set to 300 ms.

vim.o.timeoutlen = 300

Now, let’s add the custom harpoon mappings.

wk.register({
	["<leader>"] = {
		-- Harpoon
		h = {
			name = "harpoon",
			a = { mark.add_file, "Add file to harpoon" },
			l = { ui.toggle_quick_menu, "Toggle quick menu" },
			r = { mark.rm_file, "Remove file from harpoon" },
		},
	},
})

add_file is still <leader>ha, but it’s placed in a “group” with the rest of the harpoon mappings. This tree structure makes it easy to organize.

Save, restart, and press the <leader> key, and we’ll see something like:

Mappings that use the leader key

We see that our group, h, maps to “+harpoon”, where the name is taken from the special name key we defined (the + is added automatically).

If we press h, we open the harpoon group (<leader>h):

Key mappings for leader+h

Here we see where the second argument of each mapping comes into play. It adds a description of what the command does.

I think this is a great way of keeping our mappings organized and documented. I have all my custom mappings under the <leader> key, so when I don’t remember something I only need to press space, and then I can follow the beautiful UI.


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