summaryrefslogtreecommitdiff
path: root/plugin/colorscheme_persistence.lua
blob: 0b43f3f26221a35e64db0ccbc3ba1b4aed3e0b31 (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
local theme_cache_path = vim.fn.stdpath("data") .. "/last_theme.txt"
local is_programmatic_change = false

local function load_theme()
    local theme = nil

    local f = io.open(theme_cache_path, "r")
    if f then
        theme = f:read("*l")
        f:close()
    end

    if theme then
        theme = theme:match("^%s*(.-)%s*$") -- Trim any whitespace
    end

    is_programmatic_change = true
    local status = pcall(vim.cmd.colorscheme, theme)

    if not status then
        vim.cmd.colorscheme("habamax")
    end
end

local group = vim.api.nvim_create_augroup("ThemePersistance", { clear = true })

vim.api.nvim_create_autocmd("ColorScheme", {
    group = group,
    callback = function(args)
        if is_programmatic_change then
            is_programmatic_change = false
            return
        end

        local theme_name = args.match

        vim.uv.fs_open(theme_cache_path, "w", 438, function(err, fd)
            if err or not fd then
                return
            end
            vim.uv.fs_write(fd, theme_name, -1, function()
                vim.uv.fs_close(fd)
            end)
        end)
    end,
})

load_theme()