Hammerspoon 切换输入法

2,424 阅读1分钟

平时使用多种输入法,Mac 系统下切换输入法只能用系统快捷键在列表中切换,比较麻烦。 (有个设置输入法快捷键的小应用,效果很差,可以不用尝试了。快捷键也有限制。) 之前有用过 AppleScript 切换输入法,如下:

on run argv
  	tell application "System Events" to tell process "SystemUIServer"
		click (menu bar item 1 of menu bar 1 whose description is "text input")
		#click (menu item "U.S." of menu 1 of result)
		click (menu item "美国" of menu 1 of result)
	end tell
end run
on run argv
  	tell application "System Events" to tell process "SystemUIServer"
		click (menu bar item 1 of menu bar 1 whose description is "text input")
		#click (menu item "Pinyin - Simplified" of menu 1 of result)
		click (menu item "简体拼音" of menu 1 of result)
	end tell
end run
on run argv
  	tell application "System Events" to tell process "SystemUIServer"
		click (menu bar item 1 of menu bar 1 whose description is "text input")
		#click (menu item "Pinyin - Traditional" of menu 1 of result)
		click (menu item "繁体拼音" of menu 1 of result)
	end tell
end run

但,更新新版 Catalina 之后,applescript 脚本无法正常运行了。 联系苹果,官方宣称脚本没有任何变化,但情况貌似不是这样。 于是另辟蹊径,看能不能用 Hammerspoon 的 lua 去解决。找了些资料,还真给找到办法了。

先定义一个切换输入法的方法:

module = {}

module.showCurrentMethod = function ()
	hs.alert.show(hs.keycodes.currentLayout())
end

module.toUSEnglish = function ()
	-- hs.alert.show("英语")
	hs.keycodes.setLayout("U.S.")
end

module.toSimplePinyin = function ()
	-- hs.alert.show("简体拼音")
	hs.keycodes.setMethod("Pinyin - Simplified")
end

module.toThaiPinyin = function ()
	-- hs.alert.show("繁體拼音")
	hs.keycodes.setMethod("Pinyin - Traditional")
end

return module

在用绑定快捷键的方式进行调用:

...
local function windowBind(hyper, keyFuncTable)
	for key,fn in pairs(keyFuncTable) do
		hk.bind(hyper, key, fn)
	end
end
...
windowBind({"ctrl", "cmd"}, {
	e = im.toUSEnglish,
	c = im.toSimplePinyin,
	p = im.toThaiPinyin
})

更新系统之后的切换输入法问题解决了😂😂😂