summary refs log tree commit diff
path: root/.vim/plugin/darkmode.lua
blob: 6ffd06fb4fa04ae931a9d4298260d1775b09a05f (plain) (blame)
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
-- this plugin registers registers and autocommand that switches colorschemes on UIEnter based on
-- the system's preference for dark/light mode

local state = { enabled = true }

if not state.enabled then
  return
end

local set_darkmode = function(enabled)
  if enabled then
    vim.opt.background = 'dark'
    vim.cmd.colorscheme(vim.g.darkmode_colorscheme_dark or 'default')
  else
    vim.opt.background = 'light'
    vim.cmd.colorscheme(vim.g.darkmode_colorscheme_light or 'default')
  end
end

-- returns if system is configured to use darkmode
local discover = function()
  require('plenary.job')
    :new({
      command = 'porta',
      args = { 'settings', 'org.freedesktop.appearance', 'color-scheme' },
      enable_recording = true,
      on_exit = vim.schedule_wrap(function(job, exitcode)
        local darkmode_enabled = true
        local res = job:result()
        if exitcode == 0 and #res then
          darkmode_enabled = not (res[1] == 'prefer-light')
        end
        set_darkmode(darkmode_enabled)
      end),
    })
    :start()
end

-- setup autogroup
local aug = vim.api.nvim_create_augroup('darkmode', { clear = true })

-- setup color-scheme detection via desktop portal apis
vim.api.nvim_create_autocmd({ 'UIEnter', 'VimResume' }, { callback = discover, group = aug })
vim.api.nvim_create_autocmd({ 'Signal' }, { pattern = 'SIGUSR1', callback = discover, group = aug })

-- fix ColorColumn not being defined
vim.api.nvim_set_hl(0, 'ColorColumn', { link = 'CursorColumn', force = true })