Last active
November 20, 2024 08:01
-
-
Save sbliven/9bd3b158268db1768f158ba7b588b558 to your computer and use it in GitHub Desktop.
Script to toggle dark mode on and off on MacOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# usage: darkmode [dark|light] | |
set -euo pipefail | |
shopt -s nocasematch | |
if [[ $# > 0 ]]; then | |
# mode given | |
case "$1" in | |
dark) | |
DARK_MODE=true | |
;; | |
light) | |
DARK_MODE=false | |
;; | |
*) | |
echo "ERROR expected either 'dark' or 'light'" | |
exit 1 | |
;; | |
esac | |
shift | |
else | |
# Get the current macOS appearance setting | |
current_theme=$(defaults read -g AppleInterfaceStyle 2>/dev/null || true) | |
case "$current_theme" in | |
Dark) | |
DARK_MODE=false | |
;; | |
*) | |
DARK_MODE=true | |
;; | |
esac | |
fi | |
osascript -e 'tell application "System Events" to tell appearance preferences to set dark mode to '$DARK_MODE | |
if [[ "$DARK_MODE" == false ]]; then | |
echo "Switched to Light mode" | |
else | |
echo "Switched to Dark mode" | |
fi |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function! SetThemeBasedOnSystem() | |
" Check if running on macOS (Darwin) | |
if has("macunix") | |
let sys_theme = system("defaults read -g AppleInterfaceStyle 2>/dev/null") | |
" Check the output and set the background accordingly | |
if sys_theme =~ "Dark" | |
set background=dark | |
else | |
set background=light | |
endif | |
endif | |
endfunction | |
call SetThemeBasedOnSystem() | |
" Optionally, use an autocommand to refresh the background when Vim regains focus | |
augroup ThemeAutoSwitch | |
autocmd! | |
autocmd FocusGained * call SetThemeBasedOnSystem() | |
augroup END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment