popup.lua 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. local Popup = {}
  2. --- Create a new floating window
  3. -- @param config The configuration passed to vim.api.nvim_open_win
  4. -- @param win_opts The options registered with vim.api.nvim_win_set_option
  5. -- @param buf_opts The options registered with vim.api.nvim_buf_set_option
  6. -- @return A new popup
  7. function Popup:new(opts)
  8. opts = opts or {}
  9. opts.layout = opts.layout or {}
  10. opts.win_opts = opts.win_opts or {}
  11. opts.buf_opts = opts.buf_opts or {}
  12. Popup.__index = Popup
  13. local editor_layout = {
  14. height = vim.o.lines - vim.o.cmdheight - 2, -- Add margin for status and buffer line
  15. width = vim.o.columns,
  16. }
  17. local popup_layout = {
  18. relative = "editor",
  19. height = math.floor(editor_layout.height * 0.9),
  20. width = math.floor(editor_layout.width * 0.8),
  21. style = "minimal",
  22. border = "rounded",
  23. }
  24. popup_layout.row = math.floor((editor_layout.height - popup_layout.height) / 2)
  25. popup_layout.col = math.floor((editor_layout.width - popup_layout.width) / 2)
  26. local obj = {
  27. buffer = vim.api.nvim_create_buf(false, true),
  28. layout = vim.tbl_deep_extend("force", popup_layout, opts.layout),
  29. win_opts = opts.win_opts,
  30. buf_opts = opts.buf_opts,
  31. }
  32. setmetatable(obj, Popup)
  33. return obj
  34. end
  35. --- Display the popup with the provided content
  36. -- @param content_provider A function accepting the popup's layout and returning the content to display
  37. function Popup:display(content_provider)
  38. self.win_id = vim.api.nvim_open_win(self.buffer, true, self.layout)
  39. vim.lsp.util.close_preview_autocmd({ "BufHidden", "BufLeave" }, self.win_id)
  40. local lines = content_provider(self.layout)
  41. vim.api.nvim_buf_set_lines(self.bufnr, 0, -1, false, lines)
  42. -- window options
  43. for key, value in pairs(self.win_opts) do
  44. vim.api.nvim_win_set_option(self.win_id, key, value)
  45. end
  46. -- buffer options
  47. for key, value in pairs(self.buf_opts) do
  48. vim.api.nvim_buf_set_option(self.buffer, key, value)
  49. end
  50. end
  51. return Popup