Skip to content

Commit

Permalink
fix whitespace highlighting
Browse files Browse the repository at this point in the history
Before this fix, when cursor jump to another window, some char before
cursor in previous window would disappear, which probably is caused by
Conceal matches.

This fix removes cursor-related highlight matches when current window is
not focused.
  • Loading branch information
zhengpd committed Dec 7, 2024
1 parent 84a1016 commit ff65498
Showing 1 changed file with 51 additions and 11 deletions.
62 changes: 51 additions & 11 deletions lua/trim/highlighter.lua
Original file line number Diff line number Diff line change
Expand Up @@ -13,30 +13,70 @@ local has_value = function(tbl, val)
return false
end

function add_whitespace_matches()
if vim.w.trim_whitespace_match_ids == nil then
vim.w.trim_whitespace_match_ids = {
-- Trailing whitespaces
vim.fn.matchadd('ExtraWhitespace', '\\s\\+$'),
-- Trailing empty lines
vim.fn.matchadd('ExtraWhitespace', '^\\_s*\\%$'),
}
end
end

function add_cursor_matches()
if vim.w.trim_cursor_match_ids == nil then
vim.w.trim_cursor_match_ids = {
-- no highlight for whitespaces before cursor position
vim.fn.matchadd('Conceal', '\\s\\+\\%#'),
-- no highlight for lines before cursor line
vim.fn.matchadd('Conceal', '^\\_s*\\%#'),
}
end
end

function delete_whitespace_matches()
for _, matchid in ipairs(vim.w.trim_whitespace_match_ids or {}) do
vim.fn.matchdelete(matchid)
end
vim.w.trim_whitespace_match_ids = nil
end

function delete_cursor_matches()
for _, matchid in ipairs(vim.w.trim_cursor_match_ids or {}) do
vim.fn.matchdelete(matchid)
end
vim.w.trim_cursor_match_ids = nil
end

function highlighter.setup()
vim.api.nvim_set_hl(0, 'ExtraWhitespace', {
bg = config.highlight_bg,
ctermbg = config.highlight_ctermbg,
})

local augroup = vim.api.nvim_create_augroup('TrimHighlight', { clear = true })
vim.api.nvim_create_autocmd('FileType', {
vim.api.nvim_create_autocmd({ 'BufEnter', 'WinEnter' }, {
group = augroup,
pattern = '*',
callback = function()
if vim.bo.buftype == '' and not has_value(config.ft_blocklist, vim.bo.filetype) then
-- Trailing whitespaces
vim.fn.matchadd('ExtraWhitespace', '\\s\\+$')
-- no highlight for whitespaces before cursor position
vim.fn.matchadd('Conceal', '\\s\\+\\%#')

-- Trailing empty lines
vim.fn.matchadd('ExtraWhitespace', '^\\_s*\\%$')
-- no highlight for lines before cursor line
vim.fn.matchadd('Conceal', '^\\_s*\\%#')
add_whitespace_matches()
add_cursor_matches()
else
delete_whitespace_matches()
delete_cursor_matches()
end
end,
})

-- After cursor left window, the matches related to cursor would not work,
-- so clear them on BufLeave/WinLeave
vim.api.nvim_create_autocmd({ 'BufLeave', 'WinLeave' }, {
group = augroup,
callback = function()
delete_cursor_matches()
end,
})
end

return highlighter

0 comments on commit ff65498

Please sign in to comment.