summaryrefslogtreecommitdiff
path: root/lua/colorscheme_persistence.lua
blob: e5f6cda632bba93c2407e07e621dd44092e0f0d0 (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
local M = {}

-- (~/.local/share/nvim/last_theme.txt)
local theme_cache_path = vim.fn.stdpath("data") .. "/last_theme.txt"

M.is_programmatic_change = false

function M.load_theme()
    local theme = ""

    local f = io.open(theme_cache_path, "r")
    if f then
        theme = f:read("*all"):gsub("%s+", "")
        f:close()
    end

    if theme == "" then
        theme = nixCats.extra("colorscheme")
    end

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

    -- just to be safe
    if not status then
        vim.cmd.colorscheme("habamax")
    end
end

vim.api.nvim_create_autocmd("ColorScheme", {
    callback = function(args)
        -- If the change was programmatic (like at startup), don't overwrite the file
        if M.is_programmatic_change then
            M.is_programmatic_change = false -- Reset for the next manual change
            return
        end

        -- Save the new theme name to the file
        local theme_name = args.match
        local f = io.open(theme_cache_path, "w")
        if f then
            f:write(theme_name)
            f:close()
        end
    end,
})

M.load_theme()

return M