How to automatically change between light and dark themes on Linux and Gnome3?

I am using NightThemeSwitcher on Gnome3 to automatically switch between light and dark themes in the mornings and evenings. In nvim I can manually set background="light" or dark, and that changes the colors the way I want. How to automate that?

Several ideas I’ve tried, but didn’t go anywhere:

  1. NightThemeSwitcher allows setting an arbitrary command to execute when it switches. Is there something like nvim --remote "set background=\"dark\""? (Couldn’t find it on the man page, though it could be hidden in that --api-info.)
  2. nvim automatically detects what the background is on startup. Can I use that autodetection somehow?
  3. My terminal is tilix. Should that send something to its children when the switch happens?

Also, my init.vim is fairly-but-not-quite minimal. It does not set anything related to colors, except loading the julia-vim package. Happy to post it, if desired. Oh, and I am on v0.6.1, Debian testing.

Thanks for any help!

I would love to see a better solution but I have this in my init.vim

if strftime("%H") < 6
  set background=dark
elseif strftime("%H") < 17
  set background=light
else
  set background=dark
endif

This works unless you are using it during a time when it switches. Then you have to close nvim and then reopen it.

You can use neovim-remote for this, I do something like this:

IFS=$'\n'
for s in $(nvr --serverlist); do
    test ! -S "$s" && continue
    if [[ $s != "$1" && $s =~ .*/0 ]]; then
        nvr --nostart --servername "$s" --remote-expr "execute('set background=$BACKGROUND')"
    fi
done

About the if check:
$s != "$1" is only there so I can exclude a single neovim instance, useful when calling this from neovim itself as some sort of global toggle.
$s =~ .*/0 is to prevent any issues (such as nvr infinitely stalling) when there are other sockets in the neovim tempdir than the $NVIM_LISTEN_ADDRESS itself. Some plugins like fzf-lua create these.

Thanks @dckoopa , but I think nvim already does something similar? That is, on startup I see that background is already set to light or dark, depending on whether it actually is light or dark. I am precisely talking about leaving nvim up during the transition time.

1 Like

@gravndal Thanks, this seems to work!