Skip to content

Instantly share code, notes, and snippets.

@elis
Forked from jamesmacfie/README.md
Last active July 4, 2023 13:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elis/672c56a2559a6b24cf56145f67962de0 to your computer and use it in GitHub Desktop.
Save elis/672c56a2559a6b24cf56145f67962de0 to your computer and use it in GitHub Desktop.
iTerm 2 - script to change theme depending on Mac OS dark mode

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 what themes this uses

Note in the script below on lines 15 and 17 that we have a string that we're passing to iTerm2. Change 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
async def changeTheme(connection,parts):
theme_dark = "Andromeda"
theme_light = "Tango Light"
print(parts)
if "dark" in parts:
preset = await iterm2.ColorPreset.async_get(connection, theme_dark)
else:
preset = await iterm2.ColorPreset.async_get(connection, theme_light)
# Update the list of all profiles and iterate over them.
profiles=await iterm2.PartialProfile.async_query(connection)
for partial 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):
app = await iterm2.async_get_app(connection)
window = app.current_window
initial_theme = await app.async_get_theme()
await changeTheme(connection,initial_theme)
async with iterm2.VariableMonitor(connection, iterm2.VariableScopes.APP, "effectiveTheme", None) as mon:
while True:
# Block until theme changes
theme = await mon.async_get()
# Themes have space-delimited attributes, one of which will be light or dark.
parts = theme.split(" ")
await changeTheme(connection,parts)
iterm2.run_forever(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment