Skip to content

Instantly share code, notes, and snippets.

@rootiest
Last active November 27, 2024 14:40
Show Gist options
  • Save rootiest/07652ca99ed4d7f7b79e66b92d2168c2 to your computer and use it in GitHub Desktop.
Save rootiest/07652ca99ed4d7f7b79e66b92d2168c2 to your computer and use it in GitHub Desktop.
Block all keys except hjkl in buffer
-- stylua: ignore
local function setup_buffer_keymaps(bufnr)
-- Create buffer-local keymaps for 'h', 'j', 'k', 'l'
local opts = { noremap = true, silent = true, buffer = bufnr }
vim.keymap.set('n', 'h', '<cmd>echo "Pressed h"<CR>', opts)
vim.keymap.set('n', 'j', '<cmd>echo "Pressed j"<CR>', opts)
vim.keymap.set('n', 'k', '<cmd>echo "Pressed k"<CR>', opts)
vim.keymap.set('n', 'l', '<cmd>echo "Pressed l"<CR>', opts)
-- Define a function to close the buffer
local close_buffer = function()
vim.cmd('bwipeout!')
end
-- Map all printable keys (excluding 'hjkl')
local keys = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'I', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '0', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',
'-', '_', '=', '+', '[', ']', '{', '}', ';', ':', "'", '"', ',', '.', '<', '>',
'/', '?', '`', '~', '\\', '|', ' '
}
local special_keys = {
'<CR>', '<Tab>', '<Esc>', '<Space>', '<BS>', '<Up>', '<Down>', '<Left>',
'<Right>', '<Home>', '<End>', '<PageUp>', '<PageDown>', '<Insert>', '<Delete>'
}
-- Helper function to add mappings with modifiers
local function add_mappings(keysmaps, modifiers)
for _, key in ipairs(keysmaps) do
vim.keymap.set('n', key, close_buffer, opts)
for _, mod in ipairs(modifiers) do
vim.keymap.set('n', mod .. key, close_buffer, opts)
end
end
end
-- Add mappings for normal keys
add_mappings(keys, { '', '<C-', '<M-', '<A-' })
-- Add mappings for special keys
add_mappings(special_keys, { '', '<C-', '<M-', '<A-' })
end
-- Apply to the current buffer
setup_buffer_keymaps(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment