Skip to content

Commit

Permalink
feat(source): sources now always execute in the context of the main w…
Browse files Browse the repository at this point in the history
…indow even when a preview is active
  • Loading branch information
folke committed May 30, 2024
1 parent c433301 commit 4eab561
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
36 changes: 36 additions & 0 deletions lua/trouble/source.lua
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
local Preview = require("trouble.view.preview")
local Util = require("trouble.util")

---@class trouble.Source
Expand Down Expand Up @@ -68,4 +69,39 @@ function M.load()
end
end

---@param fn function
---@param ctx trouble.Source.ctx
function M.call_in_main(fn, ctx)
local current = {
win = vim.api.nvim_get_current_win(),
buf = vim.api.nvim_get_current_buf(),
cursor = vim.api.nvim_win_get_cursor(0),
}
local main = ctx and ctx.view and ctx.view:main() or current

-- if we're still in the main window,
-- we can just call the function directly
if
main.win == current.win
and main.buf == current.buf
and main.cursor[1] == current.cursor[1]
and main.cursor[2] == current.cursor[2]
then
return fn()
end

-- otherwise, we need to temporarily move to the main window
vim.api.nvim_win_call(main.win, function()
Util.noautocmd(function()
local buf = vim.api.nvim_win_get_buf(main.win)
local view = vim.fn.winsaveview()
vim.api.nvim_win_set_buf(main.win, main.buf)
vim.api.nvim_win_set_cursor(main.win, main.cursor)
fn()
vim.api.nvim_win_set_buf(main.win, buf)
vim.fn.winrestview(view)
end)
end)
end

return M
12 changes: 9 additions & 3 deletions lua/trouble/view/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ function M.new(opts)
self.items = {}
self.fetching = 0
self.nodes = {}
self._main = {}
self.cache = Cache.new("view")

self.opts.render.padding = self.opts.render.padding or vim.tbl_get(self.opts.win, "padding", "left")
Expand Down Expand Up @@ -157,7 +156,7 @@ function M:preview(item)
return Preview.open(self, item)
end

---@return {buf:number, win:number}?
---@return {buf:number, win:number, cursor:number[]}?
function M:main()
local valid = self._main
and self._main.win
Expand All @@ -167,7 +166,14 @@ function M:main()
if not valid then
self._main = self.win:find_main()
end
return self._main
if self._main then
local cursor = vim.api.nvim_win_get_cursor(self._main.win)
-- When the preview is open, use the stored main window cursor
if Preview.preview and Preview.preview.win == self._main.win then
cursor = Preview.preview.cursor
end
return { buf = self._main.buf, win = self._main.win, cursor = cursor }
end
end

function M:goto_main()
Expand Down

0 comments on commit 4eab561

Please sign in to comment.