macOS下基于Hammerspoon调用VSCode作为LaTeX文本输入源的实现问题
解决方案
1. Hammerspoon 快捷键触发 VSCode 唤起逻辑
通过 Hammerspoon 绑定快捷键,触发时自动创建/打开指定的 LaTeX 临时文件,并以 LaTeX 语言模式启动新的 VSCode 窗口:
-- 绑定快捷键:Cmd+Ctrl+L,可自行修改 hs.hotkey.bind({"cmd", "ctrl"}, "L", function() -- 替换为你的 LaTeX 临时文件路径 local tempTexFile = "/Users/your-username/Documents/LaTeXTemp.tex" -- 确保临时文件存在,不存在则创建空文件 local fileHandle = io.open(tempTexFile, "r") if not fileHandle then fileHandle = io.open(tempTexFile, "w") fileHandle:close() else fileHandle:close() end -- 启动 VSCode 新窗口,指定 LaTeX 语言模式并打开临时文件 -- 需确保 VSCode 的 `code` 命令已加入系统 PATH(VSCode 内执行 Cmd+Shift+P → 安装 Shell Command) hs.execute('code --new-window --language latex "' .. tempTexFile .. '"') -- 记录当前活跃应用,用于后续返回粘贴 _G.lastActiveApp = hs.application.frontmostApplication() end)
2. 关闭 VSCode 窗口自动复制内容(无需保存)
通过 Hammerspoon 监听 VSCode 窗口状态,当目标窗口关闭时读取临时文件内容并复制到剪贴板,可选清空临时文件:
local vscodeWindowWatcher = hs.application.watcher.new(function(appName, eventType, appObj) if appName == "Code" and eventType == hs.application.watcher.deactivated then local tempTexFile = "/Users/your-username/Documents/LaTeXTemp.tex" local fileName = hs.fs.pathToName(tempTexFile) -- 遍历 VSCode 窗口,匹配我们打开的临时文件窗口 for _, win in ipairs(appObj:allWindows()) do if win:title():find(fileName) then -- 读取文件内容 local fileHandle = io.open(tempTexFile, "r") if fileHandle then local content = fileHandle:read("*a") fileHandle:close() -- 复制内容到剪贴板 hs.pasteboard.setContents(content) -- 可选:清空临时文件,方便下次使用 local clearHandle = io.open(tempTexFile, "w") clearHandle:write("") clearHandle:close() -- 返回原应用并自动粘贴(可选) if _G.lastActiveApp then _G.lastActiveApp:activate() hs.eventtap.keyStroke({"cmd"}, "v") _G.lastActiveApp = nil end break end end end end end) vscodeWindowWatcher:start()
3. 整合「添加文本」代码片段
将你复刻的博客「添加文本」代码片段添加到 VSCode LaTeX 语言的用户代码片段中:
- 打开 VSCode,按下
Cmd+Shift+P,输入「配置用户代码片段」 - 选择「LaTeX」(或
.tex),在打开的.json文件中添加:
{ "博客添加文本片段": { "prefix": "addblogtext", // 触发前缀,可自定义 "body": [ // 这里填入你复刻的代码片段内容,每行一个字符串 "你的代码片段第一行", "你的代码片段第二行" ], "description": "快速插入博客添加文本模板" } }
后续在唤起的 VSCode 窗口中,输入你设置的前缀即可快速插入模板。
内容的提问来源于stack exchange,提问作者pbb
相关产品推荐
相关产品推荐

