Created
February 8, 2010 21:12
-
-
Save piouPiouM/298586 to your computer and use it in GitHub Desktop.
This file contains 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 | |
require ENV['TM_SUPPORT_PATH'] + "/lib/exit_codes" | |
# Converts a HTML color string to a RGB colors string. | |
# | |
# hex_to_css("#6633ff") # => rgb(102, 51, 255) | |
# hex_to_css("#63f") # => rgb(102, 51, 255) | |
# hex_to_css("#6633ff80") # => rgba(102, 51, 255, .50) | |
# hex_to_css("#63FA") # => rgba(102, 51, 255, .67) | |
# hex_to_css("#63F0") # => rgba(102, 51, 255, 0) | |
def hex_to_css(hex_color) | |
raise ArgumentError unless hex_color[0, 1] == '#' | |
hex_color.gsub!(/[#;]/, '') | |
case hex_color.length | |
when 3, 4 | |
colors = hex_color.scan(%r<[0-9a-f]>i).map { |c| (c * 2).hex } | |
when 6, 8 | |
colors = hex_color.scan(%r<[0-9a-f]{2}>i).map { |c| c.hex } | |
else | |
raise ArgumentError | |
end | |
if colors.length == 4 | |
hex_to_rgba(colors) | |
else | |
hex_to_rgb(colors) | |
end | |
end | |
# Present the colors as an RGB HTML/CSS color string. | |
def hex_to_rgb(colors) | |
"rgb(#{colors.join(', ')})" | |
end | |
# Present the colors as an RGBA (with alpha) HTML/CSS color string. | |
def hex_to_rgba(colors) | |
opacity = sprintf("%1.2f", colors.last.quo(255)).gsub(%r{([01]).00}, '\1').gsub(%r{^0\.}, '.') | |
colors.delete_at(colors.length - 1) | |
"rgba(#{colors.join(', ')}, #{opacity})" | |
end | |
raw = STDIN.read | |
begin | |
# Line | |
if ENV['TM_SELECTED_TEXT'].nil? | |
line, col = ENV['TM_CURRENT_LINE'], ENV['TM_LINE_INDEX'].to_i | |
left, before = *(line[0...col].reverse.match(/^([a-f0-9]+)?(#)/i) || [])[1..2] | |
right, after = *(line[col..-1] .match(/^([a-f0-9]+)?(;)?/i) || [])[1..2] | |
if before.nil? or (!after.nil? && right.nil? && left.nil?) | |
raise ArgumentError | |
exit 1 | |
end | |
(before ||='').reverse! | |
(left ||='').reverse! | |
right ||= '' | |
after ||= '' | |
rgb_color = hex_to_css([before, left, right].join('')) | |
color = line[0...(col - left.size - before.size)] + rgb_color + line[(col + right.size)..-1] | |
# Selected text | |
else | |
color = hex_to_css(raw) | |
end | |
print color | |
rescue ArgumentError => e | |
TextMate.exit_show_tool_tip("Not a valid color: #RGB or #RGBA or #RRGGBB or #RRGGBBAA.") | |
exit 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment