Skip to content

Commit

Permalink
feat(colorscheme): add recipe for persistent colorscheme changes
Browse files Browse the repository at this point in the history
  • Loading branch information
mehalter committed Sep 25, 2024
1 parent 90fe80b commit c1d6c0f
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions src/content/docs/recipes/colorscheme.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,74 @@ return {
This approach also handles the case when the colorscheme is not installed yet and AstroNvim will not try to set it.

:::

## Cache colorscheme

:::tip

This is available in the [AstroCommunity](https://github.com/AstroNvim/astrocommunity/tree/main/lua/astrocommunity/recipes/cache-colorscheme)

```lua title="lua/community.lua" ins={3}
return {
"AstroNvim/astrocommunity",
{ import = "astrocommunity.recipes.cache-colorscheme" },
}
```

:::

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:

```lua title="lua/plugins/cache_colorscheme.lua"
-- pick a location to cache colorscheme
local colorscheme_cache = vim.fs.joinpath(vim.fn.stdpath "state" --[[@as string]], "last_colorscheme")

--- Execute function with open file
---@param file string path to file to interact with
---@param mode openmode the mode in which to open the file
---@param callback fun(fd:file*) the callback to execute with the opened file
---@param on_error? fun(err:string) the callback to execute if unable to open the file
local function with_file(file, mode, callback, on_error)
local fd, errmsg = io.open(file, mode)
if fd then
callback(fd)
fd:close()
elseif errmsg and on_error then
on_error(errmsg)
end
end

return {
{
"AstroNvim/astroui",
--@param opts AstroUIOpts
opts = function(_, opts)
-- read colorscheme cache on open
with_file(colorscheme_cache, "r", function(file)
opts.colorscheme = file:read "*a"
end)
end,
},
{
"AstroNvim/astrocore",
---@type AstroCoreOpts
opts = {
autocmds = {
-- save colorscheme to cache on change
cache_colorscheme = {
{
event = "ColorScheme",
callback = function(args)
if args.match then
with_file(colorscheme_cache, "w+", function(file)
file:write(args.match)
end)
end
end,
},
},
},
},
},
}
```

0 comments on commit c1d6c0f

Please sign in to comment.