Created
January 12, 2012 22:47
-
-
Save kara-ryli/1603646 to your computer and use it in GitHub Desktop.
TextMate Command to toggle hex and RGB color values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
input = STDIN.read | |
match = /^\s*rgba?\(\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,[\d\.]+)?\s*\)(\s*;?)/.match(input) | |
if !match.nil? # RGB -> Hex | |
res = "#" | |
short_safe = true | |
matches = [match[1], match[2], match[3]].map do |m| | |
h = m.to_i.to_s(16) | |
if h.length == 1 | |
"0#{h}" | |
else | |
short_safe = short_safe && h[0] == h[1] | |
h | |
end | |
end | |
if short_safe | |
matches = matches.map do |m| | |
m.split("")[0] | |
end | |
end | |
res << matches.join("") | |
res << match[4] | |
res.upcase! | |
else | |
match = /^#([A-F0-9]{1,2})([A-F0-9]{1,2})([A-F0-9]{1,2})(\s*;?)$/i.match(input) | |
if match.nil? # Bad input | |
res = input | |
else # Hex -> RGB | |
res = "rgb(" | |
res << [match[1], match[2], match[3]].map do |m| | |
m << m if m.length == 1 | |
m.hex.to_s | |
end.join(",") | |
res << ")" | |
res << match[4] | |
end | |
end | |
print res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A TextMate command to toggle between Hex and RGB.
It still works if you accidentally include a semicolon at the end as well.
To create this in TextMate: