popup.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.api.nvim_command(
  40. string.format("autocmd BufHidden,BufLeave <buffer> ++once lua pcall(vim.api.nvim_win_close, %d, true)", self.win_id)
  41. )
  42. local lines = content_provider(self.layout)
  43. vim.api.nvim_buf_set_lines(self.bufnr or 0, 0, -1, false, lines)
  44. -- window options
  45. for key, value in pairs(self.win_opts) do
  46. vim.api.nvim_win_set_option(self.win_id or 0, key, value)
  47. end
  48. -- buffer options
  49. for key, value in pairs(self.buf_opts) do
  50. vim.api.nvim_buf_set_option(self.buffer, key, value)
  51. end
  52. end
  53. return Popup