From 6940cd8c6913e834254e7221ede0ca6a38c81fc0 Mon Sep 17 00:00:00 2001 From: Folke Lemaitre Date: Tue, 24 Oct 2023 09:58:23 +0200 Subject: [PATCH] feat(util): fast get_lines for a buffer --- lua/trouble/util.lua | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/lua/trouble/util.lua b/lua/trouble/util.lua index c163e295..882225f2 100644 --- a/lua/trouble/util.lua +++ b/lua/trouble/util.lua @@ -196,4 +196,40 @@ function M.split(s, c) end end +---@param buf number +---@param rows number[] 1-indexed +---@return table +function M.get_lines(buf, rows) + local uri = vim.uri_from_bufnr(buf) + + if uri:sub(1, 4) ~= "file" then + vim.fn.bufload(buf) + end + + if vim.api.nvim_buf_is_loaded(buf) then + local lines = {} ---@type table + for _, row in ipairs(rows) do + lines[row] = (vim.api.nvim_buf_get_lines(buf, row - 1, row, false) or { "" })[1] + end + return lines + end + + local filename = vim.api.nvim_buf_get_name(buf) + local fd = uv.fs_open(filename, "r", 438) + if not fd then + return {} + end + local stat = assert(uv.fs_fstat(fd)) + local data = assert(uv.fs_read(fd, stat.size, 0)) --[[@as string]] + assert(uv.fs_close(fd)) + + local ret = {} ---@type table + for row, line in M.lines(data) do + if vim.tbl_contains(rows, row) then + ret[row] = line + end + end + return ret +end + return M