Skip to content

Instantly share code, notes, and snippets.

@Mr-Jack82
Created November 19, 2023 16:53
Show Gist options
  • Select an option

  • Save Mr-Jack82/09e47918ff92946008d238fec0034e8d to your computer and use it in GitHub Desktop.

Select an option

Save Mr-Jack82/09e47918ff92946008d238fec0034e8d to your computer and use it in GitHub Desktop.
Autocmd for Neovim to be able to change keyboard layout automatically
-- Take from here: https://github.com/LazyVim/LazyVim/discussions/1346
-- Auto change input method between Normal and Insert mode
vim.api.nvim_create_autocmd({ "InsertLeave" }, {
pattern = "*",
callback = function()
-- record the input method in Insert mode
local f_input = vim.fn.stdpath("state") .. "/last_input.tmp"
os.execute("im-select > " .. f_input)
-- switch back to `ABC` input method in Normal mode
local config = package.config
if config:sub(1, 1) == "\\" then
-- windows operation
print("Windows Operation to change input method")
elseif config:sub(1, 1) == "/" then
-- unix / linux / macos operation
vim.cmd("silent ! im-select com.apple.keylayout.ABC")
else
-- other operation
print("Unrecognized operating system to change input method")
end
end,
})
vim.api.nvim_create_autocmd({ "InsertEnter" }, {
pattern = "*",
callback = function()
-- change back to the last input method used in Insert mode if it is recorded
local f_input = io.open(vim.fn.stdpath("state") .. "/last_input.tmp")
if f_input then
local input_method = f_input:read("*a")
io.close(f_input)
vim.cmd("silent ! im-select " .. input_method)
end
end,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment