Skip to content

Instantly share code, notes, and snippets.

@sigwinch28
Forked from jamesmacfie/README.md
Last active January 4, 2021 21:07
Show Gist options
  • Save sigwinch28/d8d4e77cca680fe4615c1cd1d9f69177 to your computer and use it in GitHub Desktop.
Save sigwinch28/d8d4e77cca680fe4615c1cd1d9f69177 to your computer and use it in GitHub Desktop.
iTerm 2 - script to change theme depending on Mac OS dark mode including change-on-start

How to use

In iTerm2, in the menu bar go to Scripts > Manage > New Python Script

Select Basic. Select Long-Running Daemon

Give the script a decent name (I chose auto_dark_mode.py)

Save and open the script in your editor of choice.

Copy and paste the script below and save

Go back to iTerm2, go to Scripts in the menu bar and select the script you just saved.

Try toggling Dark mode to see what happens! Reminder it's under Appearance in the System Settings

Changing which profiles this affects

On line 8 is a list of profiles. Only these profiles will have their themes changes when the system theme changes. Add or remove profiles from this list to change which profiles get updated.

Changing what themes this uses

Note in the script below on lines 6 and 7 that we have a two variables, DARK_THEME and LIGHT_THEME. Change the values of these to whatever you like. The text is whatever appears in the dropdown in the iTerm2 settings under Profile/Color for when you'd want to change the theme manually.

After you change the script you'll have to stop and start the script if it's running already

#!/usr/bin/env python3
import asyncio
import iterm2
DARK_THEME = "Solarized Dark"
LIGHT_THEME = "Light Background"
PROFILES = ["Default", "Hotkey Window"]
async def set_theme(connection, effective_theme):
# Themes have space-delimited attributes, one of which will be light or dark.
parts = effective_theme.split(" ")
if "dark" in parts:
new_theme = DARK_THEME
else:
new_theme = LIGHT_THEME
# Get the theme
preset = await iterm2.ColorPreset.async_get(connection, new_theme)
# Update the list of all profiles and iterate over them.
profiles = await iterm2.PartialProfile.async_query(connection)
for partial in profiles:
if partial.name in PROFILES:
# Fetch the full profile and then set the color preset in it.
profile = await partial.async_get_full_profile()
await profile.async_set_color_preset(preset)
async def main(connection):
# Set theme at start
app = await iterm2.async_get_app(connection)
effective_theme = await app.async_get_variable("effectiveTheme")
await set_theme(connection, effective_theme)
# Monitor changes to system theme
async with iterm2.VariableMonitor(connection, iterm2.VariableScopes.APP, "effectiveTheme", None) as mon:
while True:
# Block until effective_theme changes
effective_theme = await mon.async_get()
await set_theme(connection, effective_theme)
iterm2.run_forever(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment