summaryrefslogtreecommitdiffstats
path: root/lua/dotfiles/color.lua
blob: 6672ac0f19fefa5a99f09a1339c080828e8aa327 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
-- Theme-reaction engine. Features register a function that (re)applies their highlight settings;
-- the engine runs every registered applier whenever the active theme changes — a new colorscheme or
-- a light/dark 'background' flip — and once after startup. Appliers are wired up in
-- plugin/50-color.lua.
--
-- API:
--   register(apply) — `apply` (re)applies a feature's highlights; the engine calls it on the
--                     theme-change events above and in the post-startup pass

local M = {}

-- Registered appliers, run in registration order.
M.appliers = {}

-- Run every registered applier.
local function apply_all()
	for _, apply in ipairs(M.appliers) do
		apply()
	end
end

-- Register a highlight applier. Called immediately on the next theme-change event and in the
-- post-startup pass, so registration order is the apply order.
function M.register(apply)
	assert(type(apply) == "function", "color.register: apply must be a function")
	M.appliers[#M.appliers + 1] = apply
end

-- Re-apply on a colorscheme change and on a light/dark 'background' flip.
vim.api.nvim_create_autocmd("ColorScheme", {
	desc = "Re-apply registered highlights after a colorscheme change",
	group = vim.g.dotfiles.augroup,
	callback = apply_all,
})
vim.api.nvim_create_autocmd("OptionSet", {
	desc = "Re-apply registered highlights after a 'background' change",
	pattern = "background",
	group = vim.g.dotfiles.augroup,
	callback = apply_all,
})

-- Initial pass. OptionSet does not fire during startup (:help OptionSet), so a 'background' set by
-- local.lua (sourced from plugin/99-local.lua, i.e. during startup) is missed. Apply once on
-- VimEnter, after startup has settled 'background' to its final value.
vim.api.nvim_create_autocmd("VimEnter", {
	desc = "Apply registered highlights once startup has settled 'background'",
	group = vim.g.dotfiles.augroup,
	once = true,
	callback = apply_all,
})

return M