Skip to content

Instantly share code, notes, and snippets.

@kara-ryli
Created January 12, 2012 22:47
Show Gist options
  • Save kara-ryli/1603646 to your computer and use it in GitHub Desktop.
Save kara-ryli/1603646 to your computer and use it in GitHub Desktop.
TextMate Command to toggle hex and RGB color values
#!/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
@kara-ryli
Copy link
Author

A TextMate command to toggle between Hex and RGB.

rgb(170,170,170)      -> #AAA
rgba(170,170,170,0.5) -> #AAA
#AAA                  -> rgb(170,170,170)
#AAAAAA               -> rgb(170,170,170)

It still works if you accidentally include a semicolon at the end as well.

To create this in TextMate:

  1. Choose Bundles -> Bundle Editor -> Show Bundle Editor…
  2. Select the CSS Bundle
  3. Choose the + -> New Command
  4. Name the Command
  5. Paste the script above
  6. Use the following settings:
    • Input: "Selected Text"
    • Output: "Replace Selected Text"
    • Scope Selector: "source.css"
  7. Close the Bundle Editor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment