Here's how to automatically set Neovim's color scheme based on your system's light/dark mode in init.lua:
-- Function to detect system dark mode
local function is_dark_mode()
-- macOS
if vim.fn.has('mac') == 1 then
local handle = io.popen('defaults read -g AppleInterfaceStyle 2>/dev/null')
local result = handle:read('*a')
handle:close()
return result:match('Dark')
-- Linux (checks for common dark theme indicators)
elseif vim.fn.has('unix') == 1 then
-- Try gsettings (GNOME)
local handle = io.popen('gsettings get org.gnome.desktop.interface gtk-theme 2>/dev/null')
local result = handle:read('*a')
handle:close()
if result:lower():match('dark') then
return true
end
-- Try xfconf-query (XFCE)
handle = io.popen('xfconf-query -c xsettings -p /Net/ThemeName 2>/dev/null')
result = handle:read('*a')
handle:close()
if result:lower():match('dark') then
return true
end
-- Check environment variable
local theme = os.getenv('GTK_THEME')
if theme and theme:lower():match('dark') then
return true
end
-- Windows (checks registry)
elseif vim.fn.has('win32') == 1 then
local handle = io.popen('reg query "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize" /v AppsUseLightTheme 2>nul')
local result = handle:read('*a')
handle:close()
return result:match('0x0')
end
return false
end
-- Function to set color scheme
local function set_color_scheme()
if is_dark_mode() then
vim.o.background = 'dark'
vim.cmd('colorscheme gruvbox') -- Replace with your preferred dark theme
else
vim.o.background = 'light'
vim.cmd('colorscheme gruvbox') -- Replace with your preferred light theme
end
end
-- Set color scheme on startup
set_color_scheme()
-- Optional: Create a command to manually toggle
vim.api.nvim_create_user_command('ToggleTheme', function()
if vim.o.background == 'dark' then
vim.o.background = 'light'
else
vim.o.background = 'dark'
end
end, {})
-- Optional: Auto-refresh when Neovim gains focus (useful if you change system theme while Neovim is open)
vim.api.nvim_create_autocmd('FocusGained', {
callback = function()
set_color_scheme()
end,
})
For a more robust solution that works better across different systems, you might want to use a plugin like f-person/auto-dark-mode.nvim:
-- Using packer
use 'f-person/auto-dark-mode.nvim'
-- Or using lazy.nvim
{
'f-person/auto-dark-mode.nvim',
config = function()
require('auto-dark-mode').setup({
update_interval = 1000,
set_dark_mode = function()
vim.api.nvim_set_option('background', 'dark')
vim.cmd('colorscheme gruvbox')
end,
set_light_mode = function()
vim.api.nvim_set_option('background', 'light')
vim.cmd('colorscheme gruvbox')
end,
})
end,
}
The manual approach gives you more control but may need adjustments based on your specific system. The plugin approach is more reliable and handles edge cases better, especially for real-time theme switching.