TextMate : convertir une couleur hexadécimale en notation RGBA
Aucun outil ne sait saisir une couleur RGB(A) ? Une commande TextMate convertit votre couleur hexadécimale en notation rgba, d’un simple raccourci clavier.
Cascading Style Sheets (CSS) supporte divers formats de description des couleurs, le plus utilisé étant la notation héxadécimale #RRGGBB. L’introduction du support des couleurs Red Green Blue Alpha (RGBA) par CSS 3 a été l’occasion pour certains de découvrir les notations rgba(255, 255, 255, 1) et sa version sans gestion de l’opacité rgb(255, 255, 255).
Il faut avouer que si nous disposons d’une palette d’outils d’aide à la saisie de couleurs en notation hexadécimale, il en est rien pour insérer une couleur au format rgb[a], et cela peut agacer. Mais c’était sans compter sur TextMate !
Convertir une couleur héxadécimale en notation RGBA
La commande TextMate Convert Hex to Red Green Blue (RGB)(A) color va vous permettre de convertir via le raccourci clavier ⌘⇧X une couleur héxadécimale en son équivalent RGB(A).
Installation
Après avoir téléchargé le fichier qui suit, installez la commande d’un simple double-clique.
La nouvelle commande est maintenant disponible dans le bundle Source.
Pourquoi l’installer dans le bundle Source au lieu du bundle CSS ? Parce qu’elle peut être utile dans d’autre languages, comme JavaScript et sera ainsi disponible à tout moment, qu’importe le bundle actif.
Usage
Simple d’utilisation, positionnez-vous sur une couleur et activez la commande pour obtenir son équivalent en notation RGB :
#6633ff => rgb(102, 51, 255)
#63F => rgb(102, 51, 255)Ajoutez à une couleur héxadécimale la composante d’opacité pour remplacer la couleur par sa forme RGBA :
#6633FF80 => rgba(102, 51, 255, .50)
#63FA => rgba(102, 51, 255, .67)
#63F0 => rgba(102, 51, 255, 0)Vous pouvez également sélectionner une couleur (avec le sharp # initial) et lancer la convertion. Cela se révèle être particulièrement utile avec une sélection en colonne.
Code source
Voici le code ruby1 utilisé au sein de la commande.
#!/usr/bin/env ruby
#
# Convert a hex color into an RGB(A) color.
#
# Copyright (C) 2010 Mehdi Kabab <http://pioupioum.fr/>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
require ENV['TM_SUPPORT_PATH'] + "/lib/exit_codes"
# Converts a hex 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
color = ''
begin
# Current word
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, line by line for support of a column selection
else
raw.each do |line|
eol = line.match(/([^a-f0-9])*$/)
color << hex_to_css(line.chomp) + eol.to_s
end
end
print color
rescue ArgumentError => e
TextMate.exit_show_tool_tip("Not a valid color: #RGB or #RGBA or #RRGGBB or #RRGGBBAA")
exit 1
endNotes
-
Toute remarque ou conseil est le bienvenu. Il s’agit de mon premier script ruby… ↩
