Skip to content

Instantly share code, notes, and snippets.

@indygwyn
Forked from ttscoff/256color.rb
Created June 8, 2022 12:38
Show Gist options
  • Save indygwyn/2749746d72978f185e214eafeca67205 to your computer and use it in GitHub Desktop.
Save indygwyn/2749746d72978f185e214eafeca67205 to your computer and use it in GitHub Desktop.
256-color hex intepretation for terminal colorization
#!/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