diff --git a/lua/trouble/api.lua b/lua/trouble/api.lua index 8bb5bbd3..e30ea877 100644 --- a/lua/trouble/api.lua +++ b/lua/trouble/api.lua @@ -184,10 +184,7 @@ function M.statusline(opts) end renderer:clear() renderer:sections({ section }) - status = renderer:statusline() - if opts.hl_group then - status = require("trouble.config.highlights").fix_statusline(status, opts.hl_group) - end + status = renderer:statusline({ hl_group = opts.hl_group }) return status end, } diff --git a/lua/trouble/config/highlights.lua b/lua/trouble/config/highlights.lua index 67291aab..b88e70e1 100644 --- a/lua/trouble/config/highlights.lua +++ b/lua/trouble/config/highlights.lua @@ -93,21 +93,22 @@ function M.source(source, links) end M._fixed = {} ---@type table ----@param sl string -function M.fix_statusline(sl, statusline_hl) - local bg = vim.api.nvim_get_hl(0, { name = statusline_hl, link = false }) - bg = bg and bg.bg or nil - - return sl:gsub("%%#(.-)#", function(hl) - if not M._fixed[hl] then - local opts = vim.api.nvim_get_hl(0, { name = hl, link = false }) or {} - opts.bg = bg - local group = "TroubleStatusline" .. vim.tbl_count(M._fixed) - vim.api.nvim_set_hl(0, group, opts) - M._fixed[hl] = group - end - return "%#" .. M._fixed[hl] .. "#" - end) +---@param hl string +---@param statusline_hl string? +function M.fix_statusline_bg(hl, statusline_hl) + if not statusline_hl then + return hl + end + local key = hl .. "_" .. statusline_hl + if not M._fixed[key] then + local opts = vim.api.nvim_get_hl(0, { name = hl, link = false }) or {} + local statusline_opts = vim.api.nvim_get_hl(0, { name = statusline_hl, link = false }) + opts.bg = statusline_opts and statusline_opts.bg or nil + local group = "TroubleStatusline" .. vim.tbl_count(M._fixed) + vim.api.nvim_set_hl(0, group, opts) + M._fixed[key] = group + end + return M._fixed[key] end return M diff --git a/lua/trouble/view/text.lua b/lua/trouble/view/text.lua index a6632c2b..b0e18bfa 100644 --- a/lua/trouble/view/text.lua +++ b/lua/trouble/view/text.lua @@ -104,20 +104,26 @@ function M:nl() return self end ----@param opts? {sep?:string} +---@param opts? {sep?:string,hl_group?:string} function M:statusline(opts) local sep = opts and opts.sep or " " + local hl_group = opts and opts.hl_group or nil + sep = hl_group and ("%%#%s#%s%%*"):format(hl_group, sep) or sep local lines = {} ---@type string[] for _, line in ipairs(self._lines) do local parts = {} for _, segment in ipairs(line) do local str = segment.str:gsub("%%", "%%%%") - if segment.hl then - str = ("%%#%s#%s%%*"):format(segment.hl, str) + local fix_statusline_bg = require("trouble.config.highlights").fix_statusline_bg + local hl = segment.hl and fix_statusline_bg(segment.hl, hl_group) or hl_group + if hl then + str = ("%%#%s#%s%%*"):format(hl, str) end parts[#parts + 1] = str end - table.insert(lines, table.concat(parts, "")) + if #parts ~= 0 then + table.insert(lines, table.concat(parts, "")) + end end return table.concat(lines, sep) end