Smart Window Resizing in Neovim
2025-04-12
The last day or two, I've been refitting my Neovim windowing config. Nothing too wild, just fixing a few warts here and there. What follows is a few different snippets for different behaviors I wanted. Hopefully one of these is useful to someone, even if only as a reference (something definitely needs said about the Neovim documentation searchability situation). If you want to see these in their context, links will be left below each example. The links may fall out of date, so I've linked them to the specific commit.
Also, if you're interested in this, I credit chrisgrieser who used to run a blog called Nano Tips For Vim, which was immensely helpful to me in figuring out all of my Neovim configs but was sadly taken offline as of 2025-06-12.
Turn Off Line Numbers for Small Windows
1 local set_numbers = function(value, window)
2 vim.api.nvim_set_option_value("number", value, { win = window })
3 vim.api.nvim_set_option_value("relativenumber", value, { win = window })
4 end
5 local window_size_threshold = 40
6
7 vim.api.nvim_create_autocmd("WinResized", {
8 callback = function()
9 for _, win in ipairs(vim.api.nvim_list_wins()) do
10 local width = vim.api.nvim_win_get_width(win)
11 if width < window_size_threshold then
12 set_numbers(false, win)
13 else
14 set_numbers(true, win)
15 end
16 end
17 end,
18 })
Bring Window Into Focus
1 local win_focus = function()
2 -- Uncomment if you use either of these plugins
3 -- require("dapui").close()
4 -- require("nvim-tree.api").tree.close()
5
6 local current_win = vim.api.nvim_get_current_win()
7 local windows = vim.api.nvim_list_wins()
8 vim.api.nvim_win_set_width(0, vim.o.columns - (#windows * 20))
9 for _, win in ipairs(windows) do
10 if win ~= current_win then
11 vim.api.nvim_win_set_width(win, 20)
12 end
13 end
14 end
15
16 keymap("n", "<leader>rs", function()
17 vim.api.nvim_win_set_width(0, 20)
18 end)
19 keymap("n", "<leader>rf", win_focus)
Resizing Mappings
This requires the winresize.nvim plugin.
1 local win_resize = function(win, amt, dir)
2 return function()
3 require("winresize").resize(win, amt, dir)
4 end
5 end
6
7 wk_add("<leader>r", "Window Resize")
8 keymap("n", "<leader>rh", win_resize(0, 10, "left"))
9 keymap("n", "<leader>rj", win_resize(0, 3, "down"))
10 keymap("n", "<leader>rk", win_resize(0, 3, "up"))
11 keymap("n", "<leader>rl", win_resize(0, 10, "right"))
12 keymap("n", "<leader>r=", "<C-w>=", { desc = "Equalize Windows" })