iTerm2 automatic theme switching

iTerm2 automatic theme switching

The level and type of light is changing during the day in my workplace. In the morning it's bright sunlight, but in the evening, I use soft spot lighting.

I decided to establish automated theme switching to compensate lighting difference and make my work more comfortable.

Surprisingly the only software that does not support OC theme as a source for automated theme switching, is iTerm!

To fix it I found a script that can do such switching:

  1. Open up iTerm2
  2. Click Scripts > Manage > New Python Script in the MacOS menu bar
  3. Choose Basic as the script type
  4. Choose Long-Running Daemon as the script interval

Now, name the file however you want, like ThemeSwithDemon.py.

#!/usr/bin/env python3

import asyncio
import iterm2

async def main(connection):
    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(" ")
            if "dark" in parts:
                preset = await iterm2.ColorPreset.async_get(connection, "Smoooooth")
            else:
                preset = await iterm2.ColorPreset.async_get(connection, "Light Background")

            # 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)

iterm2.run_forever(main)

Click Scripts > auto_dark_mode.py to finally run the script. This will ask for permission and then run.

Auto-Run Scripts

If you’d like your script to launch automatically when iTerm2 starts, move it to $HOME/Library/ApplicationSupport/iTerm2/Scripts/AutoLaunch.