In general we arecused to set our colorscheme in a options file where we write our choice, but nativelly there is not a dinamic system to allow us change our colirscheme.
Just some steps
First create a theme.json
in your nvim folder
~/.config/nvim/theme.json
where we will save the color. In my case the file looks like:
{"colorscheme":"onedark"}
in your init.lua
require a file require('core.theme')
with this content:
-- ~/.config/nvim/lua/core/theme.lua
local theme_file = vim.fn.stdpath('config') .. '/theme.json'
local colorscheme = 'habamax' -- fallback
-- Tenta ler o arquivo theme.json
local function load_colorscheme()
local ok, json = pcall(vim.fn.readfile, theme_file)
if ok and json and #json > 0 then
local decoded = vim.fn.json_decode(table.concat(json, '\n'))
if decoded and decoded.colorscheme then
return decoded.colorscheme
end
end
return colorscheme
end
vim.defer_fn(function()
local cs = load_colorscheme()
local ok = pcall(vim.cmd.colorscheme, cs)
if not ok then
vim.notify('Colorscheme ' .. cs .. ' not found! Using fallback.', vim.log.levels.WARN)
pcall(vim.cmd.colorscheme, colorscheme)
end
end, 10)
Now an autocommand to detect when you choose a new theme:
vim.api.nvim_create_autocmd('ColorScheme', {
group = vim.api.nvim_create_augroup('SaveColorscheme', { clear = true }),
callback = function(args)
local theme = args.match
if theme == 'habamax' then return end -- evita salvar fallback
local path = vim.fn.stdpath('config') .. '/theme.json'
local ok, f = pcall(io.open, path, 'w')
if ok and f then
f:write(vim.json.encode({ colorscheme = theme }))
f:close()
end
end,
})
You can setup your telescope pickers.colorscheme with:
Note: Once we have an outcommand you can ignore the code below but if you want to learn how do it via telescope...
colorscheme = {
enable_preview = true,
previewer = false,
layout_config = {
height = 0.4,
width = 0.5,
},
attach_mappings = function(_, map)
local actions = require('telescope.actions')
local action_state = require('telescope.actions.state')
map('i', '<CR>', function(prompt_bufnr)
local selection = action_state.get_selected_entry()
local theme = selection.value
actions.close(prompt_bufnr)
vim.cmd.colorscheme(theme)
-- salva o tema no theme.json
local path = vim.fn.stdpath('config') .. '/theme.json'
local ok, file = pcall(io.open, path, 'w')
if ok and file then
file:write(vim.fn.json_encode({ colorscheme = theme }))
file:close()
vim.notify('Tema salvo: ' .. theme, vim.log.levels.INFO)
else
vim.notify('Erro ao salvar o tema!', vim.log.levels.ERROR)
end
end)
return true
end,
},
and let your choice be saved automatically
Top comments (0)