nvim 利用 pwsh 自动切换输入法
nvim 利用 pwsh 自动切换输入法
前言
在使用 neovide + lazyvim 的时候,每次 esc 进入 normal 模式的时候,输入法都是中文输入,作为中文系统使用者, 大部分编辑的时候都是中文输入,但是在 normal 模式下,只能使用字母,所以尝试利用 pwsh + sendkeys 来模拟按键达到切换输入法的目的
为了更好的体验,建议配置多个键盘布局,并且开启不同的窗口使用不同的输入法
解决方案
将以下代码保存到合适的路径下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 添加 Windows Forms 引用以使用 SendKeys 功能
Add-Type -AssemblyName System.Windows.Forms
function Switch-ChineseEnglishMode {
# 模拟按下 Shift 键来切换中英文输入
# [System.Windows.Forms.SendKeys]::SendWait("+")
# 或者使用以下命令模拟 Ctrl+Space 组合键
# [System.Windows.Forms.SendKeys]::SendWait("^{SPACE}")
# 通过 左 alt+Shift 切换键盘,sendwait 无法直接发送 Windows 徽标键(Win 键)组合,一般最开始编辑都是中文输入法
[System.Windows.Forms.SendKeys]::SendWait("%+")
# Write-Host "已尝试切换中英文输入模式"
}
# 调用函数切换中英文输入模式
Switch-ChineseEnglishMode
在 nvim 的配置文件中添加以下代码,调用 pwsh 脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
-- 定义 PowerShell 脚本的路径
local powershell_script_path = vim.g.baiduyun .. "\\Scripts\\PowerShell\\switch_to_english.ps1"
-- 在启动时切换到英文输入法
vim.api.nvim_create_autocmd({ "VimEnter" }, {
group = augroup("switch_input_method"),
callback = function()
if vim.fn.has("win32") or vim.fn.has("win64") == 1 then
-- 使用 PowerShell 执行脚本
vim.fn.system('powershell -NoLogo -NoProfile -ExecutionPolicy Bypass -File "' .. powershell_script_path .. '"')
end
end,
})
-- 在进入 Normal 模式时切换到英文输入法
vim.api.nvim_create_autocmd({ "InsertLeave", "InsertEnter" }, {
group = augroup("switch_input_method"),
callback = function()
if vim.fn.has("win32") or vim.fn.has("win64") == 1 then
-- 在 Windows 上执行 PowerShell 命令
vim.fn.system('powershell -NoLogo -NoProfile -ExecutionPolicy Bypass -File "' .. powershell_script_path .. '"')
end
end,
})
总结
这个主要根据个人习惯设置切换时机,通过 pwsh + sendkeys 来模拟按键达到切换输入法的目的,pwsh 的脚本可以放在任意路径下,nvim 的配置文件中调用即可
本文由作者按照
CC BY 4.0
进行授权