Last active
July 14, 2022 23:57
-
-
Save ttscoff/25a012bc903dbd9c3031e1902db7982e to your computer and use it in GitHub Desktop.
256-color hex intepretation for terminal colorization
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 | |
# frozen_string_literal: true | |
# 256-color hex interpretation for terminal colorization | |
# | |
# Usage | |
# "text".color256(foreground, background) | |
# | |
# print "Colorize this".color256('#f7921e', '#666') | |
# String category | |
module Color256 | |
def fg(fgc) | |
"\x1b[38;2;#{fgc.rgb}m" | |
end | |
def bg(bgc) | |
"\x1b[48;2;#{bgc.rgb}m" | |
end | |
def reset | |
"\x1b[0m" | |
end | |
def rgb | |
hex_string = sub(/^#?/, '') | |
hex_string = hex_string.split(//).map { |a| a * 2 }.join('') if hex_string =~ /^#?[a-f0-9]{3}$/i | |
parts = hex_string.match(/#?(?<r>..)(?<g>..)(?<b>..)/) | |
t = [] | |
%w[r g b].each do |e| | |
t << parts[e].hex | |
end | |
t.join(';') | |
end | |
def color256(fgc, bgc = nil) | |
out = '' | |
out += fg(fgc) | |
out += bg(bgc) if bgc | |
out += self | |
out + reset | |
end | |
end | |
class ::String | |
include Color256 | |
end | |
def test | |
256.times do |r| | |
256.times do |g| | |
256.times do |b| | |
c = '' | |
[r, g, b].each { |comp| c += format('%02x', comp) } | |
print ' '.color256('000', c) | |
end | |
end | |
end | |
end | |
if __FILE__ == $0 | |
print ARGV[0].color256(ARGV[1], ARGV[2]) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should be fixed now.