Created
September 19, 2025 06:13
-
-
Save CarsonSlovoka/e228da4f10f61e448f3bbba953b0e638 to your computer and use it in GitHub Desktop.
nvim自動開啟終端機,並且能補獲所有stdout的內容
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- 定義一個函數來開啟互動式 terminal 並捕捉 stdout | |
| local function open_interactive_terminal() | |
| -- 用來儲存 stdout 的結果 | |
| local output = {} | |
| -- 開啟新窗口並啟動 terminal | |
| vim.cmd('new') | |
| local buf = vim.api.nvim_get_current_buf() | |
| -- 使用 termopen 開啟一個互動式 terminal | |
| local job_id = vim.fn.termopen(vim.o.shell, { | |
| on_exit = function(_, exit_code) | |
| -- 當 terminal 退出時,提取 buffer 內容 | |
| local lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false) | |
| for _, line in ipairs(lines) do | |
| if line ~= "" then -- 忽略空行 | |
| table.insert(output, line) | |
| end | |
| end | |
| -- 關閉 terminal 窗口 | |
| vim.api.nvim_buf_delete(buf, { force = true }) | |
| -- 印出捕捉到的 stdout 結果 | |
| print("Terminal output:") | |
| for _, line in ipairs(output) do | |
| print(line) | |
| end | |
| end | |
| }) | |
| -- 檢查是否成功啟動 terminal | |
| if job_id <= 0 then | |
| print("Failed to start terminal") | |
| vim.api.nvim_buf_delete(buf, { force = true }) | |
| return | |
| end | |
| -- 自動進入 insert mode,讓用戶可以直接輸入指令 | |
| vim.cmd('startinsert') | |
| end | |
| -- 綁定一個命令來調用此函數 | |
| vim.api.nvim_create_user_command('Test', open_interactive_terminal, {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment