Skip to content

Instantly share code, notes, and snippets.

@sneeu
Created April 17, 2009 09:33
Show Gist options
  • Save sneeu/96945 to your computer and use it in GitHub Desktop.
Save sneeu/96945 to your computer and use it in GitHub Desktop.
A TextMate command that converts rgb(x, y, z) to #pqr
#!/usr/bin/env python
# See a demo: <http://www.vimeo.com/4195472>
# Here are the settings: <http://www.quicksnapper.com/sneeu/image/css-colour-convert-settings>
import os
import re
import sys
_HEX_COLOUR_RE = re.compile('#[0-9a-f]{3}|[0-9a-f]{6}', re.IGNORECASE)
def _split_list(my_list, sublist_length):
"""
Splits a list of length n into a list of lists of length sublist_length.
"""
list_of_lists = []
for i in xrange(0, len(my_list), sublist_length):
list_of_lists.append(my_list[i:i + sublist_length])
return list_of_lists
def _convert_3_to_6(text):
"""
Expands a three digit hex code into a six digit hex code.
>>> _convert_3_to_6('333')
333333
>>> _convert_3_to_6('888')
888888
"""
r = ''
for c in text:
r = r + c + c
return r
def _convert_6_to_3(text):
"""
Potentially converts a 6 digit hex code into a three digit hex code.
>>> _convert_6_to_3('665544')
654
>>> _convert_6_to_3('665543')
665543
"""
r = ''
for i in range(0, len(text), 2):
if text[i] == text[i + 1]:
r += text[i]
else:
return text
return r
def hex_to_ints(h):
"""Converts a list of hex values, into a list of base 10 values."""
return [str(int(x, 16)) for x in h]
def ints_to_hex(i):
"""Converts a list of base 10 values, into a list of hex values."""
return [hex(int(n))[2:].rjust(2, '0') for n in i]
def bidi_colour(text):
"""
Changes a colour from a hex code to an rgb(), or an rgb() to a hex colour
code.
>>> bidi_colour(bidi_colour('#333'))
#333
>>> bidi_colour(bidi_colour('#123456'))
#123456
>>> bidi_colour(bidi_colour('#665544'))
#654
"""
if _HEX_COLOUR_RE.match(text):
text = text[1:].strip()
if len(text) == 3:
text = _convert_3_to_6(text)
text = _split_list(text, len(text) / 3)
colour = 'rgb(%s)' % ', '.join(hex_to_ints(text))
elif text.lower().startswith('rgb('):
colour = '#' + _convert_6_to_3(''.join(ints_to_hex(
text.lower().replace('rgb(', '').replace(')', '').split(','))))
else:
colour = text
return colour
if __name__ == '__main__':
sys.stdout.write(bidi_colour(os.environ['TM_SELECTED_TEXT']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment