Skip to content

Commit

Permalink
perf(preview): re-use existing preview when preview is for the same file
Browse files Browse the repository at this point in the history
  • Loading branch information
folke committed May 31, 2024
1 parent 6053627 commit a415b64
Showing 1 changed file with 30 additions and 26 deletions.
56 changes: 30 additions & 26 deletions lua/trouble/view/preview.lua
Original file line number Diff line number Diff line change
Expand Up @@ -71,52 +71,56 @@ function M.create(item, opts)
end
end

return buf
end

---@param view trouble.View
---@param item trouble.Item
---@param opts? {scratch?:boolean}
function M.open(view, item, opts)
if M.item() == item then
return
end
if M.preview and M.preview.item.filename ~= item.filename then
M.close()
end

if not M.preview then
local buf = M.create(item, opts)
if not buf then
return
end

M.preview = M.preview_win(buf, view)

M.preview.buf = buf
M.preview.item = item
end

Render.reset(M.preview.buf)

-- make sure we highlight at least one character
local end_pos = { item.end_pos[1], item.end_pos[2] }
if end_pos[1] == item.pos[1] and end_pos[2] == item.pos[2] then
end_pos[2] = end_pos[2] + 1
end

-- highlight the line
Util.set_extmark(buf, Render.ns, item.pos[1] - 1, 0, {
Util.set_extmark(M.preview.buf, Render.ns, item.pos[1] - 1, 0, {
end_row = end_pos[1],
hl_group = "CursorLine",
hl_eol = true,
strict = false,
})

-- highlight the range
Util.set_extmark(buf, Render.ns, item.pos[1] - 1, item.pos[2], {
Util.set_extmark(M.preview.buf, Render.ns, item.pos[1] - 1, item.pos[2], {
end_row = end_pos[1] - 1,
end_col = end_pos[2],
hl_group = "TroublePreview",
strict = false,
})

return buf
end

---@param view trouble.View
---@param item trouble.Item
---@param opts? {scratch?:boolean}
function M.open(view, item, opts)
if M.item() == item then
return
end
if M.preview then
M.close()
end

local buf = M.create(item, opts)
if not buf then
return
end

M.preview = M.preview_win(buf, view)

M.preview.buf = buf
M.preview.item = item

-- no autocmds should be triggered. So LSP's etc won't try to attach in the preview
Util.noautocmd(function()
if pcall(vim.api.nvim_win_set_cursor, M.preview.win, item.pos) then
Expand Down

0 comments on commit a415b64

Please sign in to comment.