summary refs log tree commit diff
path: root/.vim/plugin/syncbg.lua
blob: c11bef6659b9a99e565414b079b140766d0bd655 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
-- this plugin registers two autocmds that trigger when openeing and closing the editor, setting the
-- background of the terminal to the color used by our colorscheme using CSI control codes.

local state = { enabled = false }

if not state.enabled then
  return
end

local set_bg = function(clear)
  if not (state.tty and state.normal) then
    return
  end
  if clear then
    -- emit CSI to unset custom background
    os.execute('printf "\\033]111\\007" > ' .. state.tty)
  else
    -- emit CSI to change terminal background to Normal.bg
    os.execute(
      'printf "\\033]11;' .. string.format('#%06x', state.normal.bg) .. '\\007" > ' .. state.tty
    )
    -- set colorscheme Normal.bg to NONE, making it transparent
    vim.cmd([[hi Normal ctermbg=NONE guibg=NONE]])
  end
end

local discover = function()
  if not state.tty then
    -- get tty handle
    local ok, tty_handle = pcall(io.popen, 'tty')
    if (not ok) or tty_handle == nil then
      return
    end
    local tty = tty_handle:read('*l')
    tty_handle:close()
    if tty:find('not a tty') then
      return
    end
    state.tty = tty
  end

  if not state.normal then
    -- get colorscheme Normal highlight
    local normal = vim.api.nvim_get_hl(0, { name = 'Normal', create = false })
    if normal.bg == nil then
      return
    end
    -- cache old value for use with VimResume
    state.normal = normal
  end

  -- vim.notify('syncbg: ' .. vim.inspect(state), vim.log.levels.DEBUG)
end

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

-- register update hook
vim.api.nvim_create_autocmd({ 'ColorScheme', 'UIEnter', 'VimResume' }, {
  group = aug,
  callback = vim.schedule_wrap(function()
    discover()
    set_bg(false)
  end),
})

-- register reset hook
vim.api.nvim_create_autocmd({ 'UILeave' }, {
  group = aug,
  callback = vim.schedule_wrap(function()
    set_bg(true)
  end),
})