Created
April 12, 2020 05:52
-
-
Save danielwhite/27e936e66ffaf44cab22adf3e8c3a12f to your computer and use it in GitHub Desktop.
Inverted, safe, foreground and background ANSI escape codes
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
/* | |
Create a string usage a web-safe version of the specified background color. | |
The foreground will be set to an inverse color for legibility. | |
Untested and definitely broken. | |
*/ | |
func decorate(bgColor color.Color, s string) string { | |
fgColor := inverse(bgColor) | |
return setBackground(bgColor) + setForeground(fgColor) + code + "\u001b[0m" | |
} | |
func setForeground(c color.Color) string { | |
return fmt.Sprintf("\x1b[38;5;%dm", websafeCode(c)) | |
} | |
func setBackground(c color.Color) string { | |
return fmt.Sprintf("\x1b[48;5;%dm", websafeCode(c)) | |
} | |
func inverse(c color.Color) color.Color { | |
r, g, b, a := c.RGBA() | |
r = a - r | |
g = a - g | |
b = a - b | |
return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)} | |
} | |
func websafeCode(c color.Color) int { | |
// This doesn't really work. | |
var p color.Palette = palette.WebSafe | |
return p.Index(c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment