How to invert hex colour codes

The problem: Invert the colours of a Sublime Text 2 colour theme, so that when I invert the screen on my MacBook the colours are as if they weren’t inverted.

The solution: Write a python script that matches the hex colour codes (e.g. #ffffff) in the colour theme configuration file against a regular expression, and replace the hex colour codes with their inverse.

The code:

Things to note: The python interpreter returns hex numbers with a preceding ‘0x’, so hex(255) yields 0xff. That’s why we use [2:] to grab just the last two characters of the value. The regular expression here is used to match six character RGB codes as well as eight character ARGB codes. RGB codes can also be expressed as three characters but in the tmTheme file I was working with none were present.

Background: Last year I was diagnosed with cataracts in both eyes. A white back-lit program or webpage is particularly difficult to read because of the glare caused by the white light. Fortunately on Macs ctrl + alt + cmd + 8 inverts the screen to help alleviate this. Unfortunately this meant by code editor (Sublime Text 2) got inverted too. So rather than having to flick back and forth between modes, when working between Sublime and the browser I thought it’d be best to invert Sublime to have my Mac screen consistently inverted.

One thought on “How to invert hex colour codes

Leave a Reply

Your email address will not be published. Required fields are marked *