Created
March 26, 2024 16:55
-
-
Save Makaze/f2b447a9c4088910158bb70d5e833019 to your computer and use it in GitHub Desktop.
Continually replace buffer contents with a command. A scrollable alternative to the linux `watch` command
This file contains 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
local M = {} | |
local A = vim.api | |
M.buf = nil | |
-- Replace buffer's contents with a command and preserve the cursor | |
M.update = function(command) | |
return function() | |
-- Save current cursor position | |
local saveCursor = A.nvim_win_get_cursor(0) | |
-- Execute your command and capture its output | |
local output = vim.fn.systemlist(command) | |
-- Strip ANSI color codes from the output | |
local strippedOutput = {} | |
for _, line in ipairs(output) do | |
local strippedLine = line:gsub("\27%[[%d;]*[mK]", "") -- Remove ANSI escape sequences | |
table.insert(strippedOutput, strippedLine) | |
end | |
-- Clear the buffer and insert the stripped output | |
A.nvim_buf_set_lines(M.buf, 0, -1, false, strippedOutput) | |
-- Restore cursor position | |
A.nvim_win_set_cursor(0, saveCursor) | |
end | |
end | |
-- Continually replace buffer contents with command | |
M.start = function(command, refresh_rate) | |
local uv = vim.loop or vim.uv | |
-- Create a new buffer | |
if not M.buf then | |
M.buf = A.nvim_create_buf(false, true) | |
-- Automatically delete buffer when no longer visible | |
vim.api.nvim_set_option_value("bufhidden", "wipe", { buf = M.buf }) | |
-- A.nvim_command "split" | |
A.nvim_win_set_buf(0, M.buf) | |
end | |
-- A.nvim_set_current_buf(buf) | |
-- Set up a timer to run the function every 500ms | |
M.watch_timer = uv.new_timer() | |
M.watch_timer:start(refresh_rate, refresh_rate, vim.schedule_wrap(M.update(command))) | |
local group = A.nvim_create_augroup("WatchCleanUp", { clear = true }) | |
-- Stop the timer when the buffer is unloaded or when quitting Neovim | |
A.nvim_create_autocmd({ "BufUnload", "VimLeavePre" }, { | |
group = group, | |
buffer = M.buf, | |
callback = M.stop, | |
}) | |
end | |
M.stop = function() | |
M.buf = nil | |
M.watch_timer:stop() | |
end | |
return M |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment