Skip to content

Commit c1d6c0f

Browse files
committed
feat(colorscheme): add recipe for persistent colorscheme changes
1 parent 90fe80b commit c1d6c0f

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

src/content/docs/recipes/colorscheme.mdx

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,74 @@ return {
8989
This approach also handles the case when the colorscheme is not installed yet and AstroNvim will not try to set it.
9090

9191
:::
92+
93+
## Cache colorscheme
94+
95+
:::tip
96+
97+
This is available in the [AstroCommunity](https://github.com/AstroNvim/astrocommunity/tree/main/lua/astrocommunity/recipes/cache-colorscheme)
98+
99+
```lua title="lua/community.lua" ins={3}
100+
return {
101+
"AstroNvim/astrocommunity",
102+
{ import = "astrocommunity.recipes.cache-colorscheme" },
103+
}
104+
```
105+
106+
:::
107+
108+
Some users may want to persist the last chosen colorscheme rather than always using the value set in their user configuration on startup. This can be easily implemented within your plugin configuration with the following code:
109+
110+
```lua title="lua/plugins/cache_colorscheme.lua"
111+
-- pick a location to cache colorscheme
112+
local colorscheme_cache = vim.fs.joinpath(vim.fn.stdpath "state" --[[@as string]], "last_colorscheme")
113+
114+
--- Execute function with open file
115+
---@param file string path to file to interact with
116+
---@param mode openmode the mode in which to open the file
117+
---@param callback fun(fd:file*) the callback to execute with the opened file
118+
---@param on_error? fun(err:string) the callback to execute if unable to open the file
119+
local function with_file(file, mode, callback, on_error)
120+
local fd, errmsg = io.open(file, mode)
121+
if fd then
122+
callback(fd)
123+
fd:close()
124+
elseif errmsg and on_error then
125+
on_error(errmsg)
126+
end
127+
end
128+
129+
return {
130+
{
131+
"AstroNvim/astroui",
132+
--@param opts AstroUIOpts
133+
opts = function(_, opts)
134+
-- read colorscheme cache on open
135+
with_file(colorscheme_cache, "r", function(file)
136+
opts.colorscheme = file:read "*a"
137+
end)
138+
end,
139+
},
140+
{
141+
"AstroNvim/astrocore",
142+
---@type AstroCoreOpts
143+
opts = {
144+
autocmds = {
145+
-- save colorscheme to cache on change
146+
cache_colorscheme = {
147+
{
148+
event = "ColorScheme",
149+
callback = function(args)
150+
if args.match then
151+
with_file(colorscheme_cache, "w+", function(file)
152+
file:write(args.match)
153+
end)
154+
end
155+
end,
156+
},
157+
},
158+
},
159+
},
160+
},
161+
}
162+
```

0 commit comments

Comments
 (0)