fix(lsp): limit number of created highlight groups (#39133)

* fix(api): allow silencing "Too many highlight groups" error

Problem: Using Lua's `vim.api.nvim_set_hl(0, 'New', {...})` can fail if
  there are too many existing highlight groups. However, this error can
  not be silenced with `pcall`.

Solution: Make it possible to silence in `nvim_set_hl` and
  `nvim_get_hl_id_by_name`.

* fix(lsp): limit number of groups created by `document_color()`

Problem: A file can contain many string colors that would be highlighted
  by an LSP server. If this number crosses 19999 (maximum number of
  allowed highlight groups), there are general issues with creating
  other highlight groups, which can break functionality outside of
  `vim.lsp.document_color`.

Solution: Limit number of highlight groups that are created by
  `vim.lsp.document_color` to 10000 (half of allowed maximum).
  This is not a 100% solution (since there can exist more than 10000
  other highlight groups), but explicitly checking number of groups is
  slow and 10000 should (hopefully) be enough for most use cases.
This commit is contained in:
Evgeni Chasnovski
2026-04-18 03:16:11 +03:00
committed by GitHub
parent eb569a695f
commit 7219b816ea
3 changed files with 45 additions and 16 deletions

View File

@@ -252,12 +252,25 @@ describe('API: set highlight', function()
it('does not segfault on invalid group name #20009', function()
eq(
"Invalid highlight name: 'foo bar'",
'Vim:E5248: Invalid character in group name',
pcall_err(api.nvim_set_hl, 0, 'foo bar', { bold = true })
)
assert_alive()
end)
it('can be silenced if there are too many groups #38930', function()
local n_groups = vim.tbl_count(api.nvim_get_hl(0, {}))
local has_fail = false
for i = n_groups + 1, 20000 do
local _, msg = pcall(api.nvim_set_hl, 0, 'New_' .. i, { fg = '#000000' })
local is_fail = type(msg) == 'string'
and msg:find('Too many highlight and syntax groups$') ~= nil
has_fail = has_fail or is_fail
end
eq('', exec_capture('messages'))
eq(true, has_fail)
end)
it('update=true sets only specified keys', function()
api.nvim_set_hl(0, 'TestGroup', { fg = '#ff0000', bg = '#0000ff', bold = true })
api.nvim_set_hl(0, 'TestGroup', { bg = '#00ff00', update = true })