chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
commit
7e7d249099
1134 files changed
+433629
No files matched your search
@@ -0,0 +1,51 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package style
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Context struct {
|
||||
AllowEscapeCodes bool
|
||||
}
|
||||
|
||||
func (self *Context) SprintFunc(spec string) func(args ...any) string {
|
||||
p := prefix_for_spec(spec)
|
||||
s := suffix_for_spec(spec)
|
||||
|
||||
return func(args ...any) string {
|
||||
body := fmt.Sprint(args...)
|
||||
if !self.AllowEscapeCodes {
|
||||
return body
|
||||
}
|
||||
b := strings.Builder{}
|
||||
b.Grow(len(p) + len(body) + len(s))
|
||||
b.WriteString(p)
|
||||
b.WriteString(body)
|
||||
b.WriteString(s)
|
||||
return b.String()
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Context) UrlFunc(spec string) func(string, string) string {
|
||||
p := prefix_for_spec(spec)
|
||||
s := suffix_for_spec(spec)
|
||||
|
||||
return func(url, text string) string {
|
||||
if !self.AllowEscapeCodes {
|
||||
return text
|
||||
}
|
||||
uc := url_code{url: url}
|
||||
up, us := uc.prefix(), uc.suffix()
|
||||
b := strings.Builder{}
|
||||
b.Grow(len(p) + len(up) + len(text) + len(s) + len(us))
|
||||
b.WriteString(p)
|
||||
b.WriteString(up)
|
||||
b.WriteString(text)
|
||||
b.WriteString(us)
|
||||
b.WriteString(s)
|
||||
return b.String()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
// License: GPLv3 Copyright: 2025, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package style
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
|
||||
// Color space conversion functions for wide gamut color support
|
||||
// Implements OKLCH, Display P3, and CIE LAB color formats with
|
||||
// CSS Color Module Level 4 gamut mapping.
|
||||
|
||||
// srgbToLinear converts sRGB component (0-1) to linear light
|
||||
func srgbToLinear(c float64) float64 {
|
||||
if c <= 0.04045 {
|
||||
return c / 12.92
|
||||
}
|
||||
return math.Pow((c+0.055)/1.055, 2.4)
|
||||
}
|
||||
|
||||
// linearToSrgb converts linear light component (0-1) to sRGB
|
||||
func linearToSrgb(c float64) float64 {
|
||||
if c <= 0.0031308 {
|
||||
return c * 12.92
|
||||
}
|
||||
return 1.055*math.Pow(c, 1.0/2.4) - 0.055
|
||||
}
|
||||
|
||||
// oklabToLinearSrgb converts OKLab to linear sRGB
|
||||
func oklabToLinearSrgb(l, a, b float64) (float64, float64, float64) {
|
||||
l_ := l + 0.3963377774*a + 0.2158037573*b
|
||||
m_ := l - 0.1055613458*a - 0.0638541728*b
|
||||
s_ := l - 0.0894841775*a - 1.2914855480*b
|
||||
|
||||
l_cubed := l_ * l_ * l_
|
||||
m_cubed := m_ * m_ * m_
|
||||
s_cubed := s_ * s_ * s_
|
||||
|
||||
r := +4.0767416621*l_cubed - 3.3077115913*m_cubed + 0.2309699292*s_cubed
|
||||
g := -1.2684380046*l_cubed + 2.6097574011*m_cubed - 0.3413193965*s_cubed
|
||||
b_val := -0.0041960863*l_cubed - 0.7034186147*m_cubed + 1.7076147010*s_cubed
|
||||
|
||||
return r, g, b_val
|
||||
}
|
||||
|
||||
// oklchToSrgb converts OKLCH to sRGB (without gamut mapping)
|
||||
func oklchToSrgb(l, c, h float64) (float64, float64, float64) {
|
||||
// Convert OKLCH to OKLab
|
||||
hRad := h * math.Pi / 180.0
|
||||
a := c * math.Cos(hRad)
|
||||
b := c * math.Sin(hRad)
|
||||
|
||||
// Convert OKLab to linear sRGB
|
||||
rLin, gLin, bLin := oklabToLinearSrgb(l, a, b)
|
||||
|
||||
// Apply sRGB transfer function
|
||||
r := linearToSrgb(rLin)
|
||||
g := linearToSrgb(gLin)
|
||||
bVal := linearToSrgb(bLin)
|
||||
|
||||
return r, g, bVal
|
||||
}
|
||||
|
||||
// srgbToOklab converts sRGB to OKLab (for deltaE calculations)
|
||||
func srgbToOklab(r, g, b float64) (float64, float64, float64) {
|
||||
rLin := srgbToLinear(r)
|
||||
gLin := srgbToLinear(g)
|
||||
bLin := srgbToLinear(b)
|
||||
|
||||
l_ := 0.4122214708*rLin + 0.5363325363*gLin + 0.0514459929*bLin
|
||||
m_ := 0.2119034982*rLin + 0.6806995451*gLin + 0.1073969566*bLin
|
||||
s_ := 0.0883024619*rLin + 0.2817188376*gLin + 0.6299787005*bLin
|
||||
|
||||
l_ = math.Cbrt(l_)
|
||||
m_ = math.Cbrt(m_)
|
||||
s_ = math.Cbrt(s_)
|
||||
|
||||
l := 0.2104542553*l_ + 0.7936177850*m_ - 0.0040720468*s_
|
||||
a := 1.9779984951*l_ - 2.4285922050*m_ + 0.4505937099*s_
|
||||
bVal := 0.0259040371*l_ + 0.7827717662*m_ - 0.8086757660*s_
|
||||
|
||||
return l, a, bVal
|
||||
}
|
||||
|
||||
// deltaEOk calculates perceptual color difference in OKLab space
|
||||
func deltaEOk(lab1, lab2 [3]float64) float64 {
|
||||
dl := lab1[0] - lab2[0]
|
||||
da := lab1[1] - lab2[1]
|
||||
db := lab1[2] - lab2[2]
|
||||
return math.Sqrt(dl*dl + da*da + db*db)
|
||||
}
|
||||
|
||||
// oklchToSrgbGamutMap converts OKLCH to sRGB with CSS Color Module Level 4 gamut mapping
|
||||
func oklchToSrgbGamutMap(l, c, h float64) (float64, float64, float64) {
|
||||
// Constants from CSS Color Module Level 4
|
||||
const jnd = 0.02 // Just Noticeable Difference threshold
|
||||
const minConvergence = 0.0001 // Binary search precision
|
||||
const epsilon = 0.00001 // Small value for floating point comparisons
|
||||
|
||||
// Edge cases: pure black or white
|
||||
if l <= 0.0 {
|
||||
return 0.0, 0.0, 0.0
|
||||
}
|
||||
if l >= 1.0 {
|
||||
return 1.0, 1.0, 1.0
|
||||
}
|
||||
|
||||
// If chroma is very small, color is achromatic
|
||||
if c < epsilon {
|
||||
gray := linearToSrgb(l)
|
||||
return gray, gray, gray
|
||||
}
|
||||
|
||||
// Try the original color first
|
||||
r, g, b := oklchToSrgb(l, c, h)
|
||||
|
||||
// Check if already in gamut
|
||||
if r >= 0.0 && r <= 1.0 && g >= 0.0 && g <= 1.0 && b >= 0.0 && b <= 1.0 {
|
||||
return r, g, b
|
||||
}
|
||||
|
||||
// Binary search for maximum in-gamut chroma
|
||||
lowChroma := 0.0
|
||||
highChroma := c
|
||||
|
||||
for (highChroma - lowChroma) > minConvergence {
|
||||
midChroma := (highChroma + lowChroma) * 0.5
|
||||
|
||||
// Try this chroma value
|
||||
rTest, gTest, bTest := oklchToSrgb(l, midChroma, h)
|
||||
|
||||
// Check if in gamut (before clipping)
|
||||
inGamut := rTest >= 0.0 && rTest <= 1.0 &&
|
||||
gTest >= 0.0 && gTest <= 1.0 &&
|
||||
bTest >= 0.0 && bTest <= 1.0
|
||||
|
||||
if inGamut {
|
||||
// In gamut - try higher chroma
|
||||
lowChroma = midChroma
|
||||
} else {
|
||||
// Out of gamut - clip and check deltaE
|
||||
rClipped := math.Max(0.0, math.Min(1.0, rTest))
|
||||
gClipped := math.Max(0.0, math.Min(1.0, gTest))
|
||||
bClipped := math.Max(0.0, math.Min(1.0, bTest))
|
||||
|
||||
// Convert both to OKLab for comparison
|
||||
lTest, aTest, bTestLab := srgbToOklab(rTest, gTest, bTest)
|
||||
testLab := [3]float64{lTest, aTest, bTestLab}
|
||||
|
||||
lClip, aClip, bClip := srgbToOklab(rClipped, gClipped, bClipped)
|
||||
clippedLab := [3]float64{lClip, aClip, bClip}
|
||||
|
||||
// Calculate perceptual difference
|
||||
de := deltaEOk(testLab, clippedLab)
|
||||
|
||||
if de < jnd {
|
||||
// Difference is imperceptible - accept this chroma
|
||||
lowChroma = midChroma
|
||||
} else {
|
||||
// Difference is noticeable - reduce chroma more
|
||||
highChroma = midChroma
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Use the final chroma value and clip to ensure in-gamut
|
||||
rFinal, gFinal, bFinal := oklchToSrgb(l, lowChroma, h)
|
||||
return math.Max(0.0, math.Min(1.0, rFinal)),
|
||||
math.Max(0.0, math.Min(1.0, gFinal)),
|
||||
math.Max(0.0, math.Min(1.0, bFinal))
|
||||
}
|
||||
|
||||
// labToOklch converts CIE LAB to OKLCH for gamut mapping
|
||||
func labToOklch(l, a, b float64) (float64, float64, float64) {
|
||||
// LAB to XYZ (using D65 illuminant)
|
||||
y := (l + 16) / 116
|
||||
x := a/500 + y
|
||||
z := y - b/200
|
||||
|
||||
fInv := func(t float64) float64 {
|
||||
delta := 6.0 / 29.0
|
||||
if t > delta {
|
||||
return t * t * t
|
||||
}
|
||||
return 3 * delta * delta * (t - 4.0/29.0)
|
||||
}
|
||||
|
||||
// D65 white point
|
||||
const xN = 0.95047
|
||||
const yN = 1.00000
|
||||
const zN = 1.08883
|
||||
|
||||
xVal := xN * fInv(x)
|
||||
yVal := yN * fInv(y)
|
||||
zVal := zN * fInv(z)
|
||||
|
||||
// XYZ to linear sRGB
|
||||
rLin := +3.2404542*xVal - 1.5371385*yVal - 0.4985314*zVal
|
||||
gLin := -0.9692660*xVal + 1.8760108*yVal + 0.0415560*zVal
|
||||
bLin := +0.0556434*xVal - 0.2040259*yVal + 1.0572252*zVal
|
||||
|
||||
// Convert to OKLab
|
||||
l_ := 0.4122214708*rLin + 0.5363325363*gLin + 0.0514459929*bLin
|
||||
m_ := 0.2119034982*rLin + 0.6806995451*gLin + 0.1073969566*bLin
|
||||
s_ := 0.0883024619*rLin + 0.2817188376*gLin + 0.6299787005*bLin
|
||||
|
||||
l_ = math.Cbrt(l_)
|
||||
m_ = math.Cbrt(m_)
|
||||
s_ = math.Cbrt(s_)
|
||||
|
||||
lOk := 0.2104542553*l_ + 0.7936177850*m_ - 0.0040720468*s_
|
||||
aOk := 1.9779984951*l_ - 2.4285922050*m_ + 0.4505937099*s_
|
||||
bOk := 0.0259040371*l_ + 0.7827717662*m_ - 0.8086757660*s_
|
||||
|
||||
// Convert OKLab to OKLCH
|
||||
c := math.Sqrt(aOk*aOk + bOk*bOk)
|
||||
h := math.Atan2(bOk, aOk) * 180.0 / math.Pi
|
||||
if h < 0 {
|
||||
h += 360
|
||||
}
|
||||
|
||||
return lOk, c, h
|
||||
}
|
||||
|
||||
// parseOklch parses OKLCH color: oklch(l c h) or oklch(l, c, h)
|
||||
func parseOklch(spec string) (RGBA, error) {
|
||||
spec = strings.TrimRight(spec, ")")
|
||||
parts := splitColorComponents(spec)
|
||||
|
||||
if len(parts) != 3 {
|
||||
return RGBA{}, errors.New("not enough parts")
|
||||
}
|
||||
|
||||
l, err := parseFloatValue(parts[0])
|
||||
if err != nil {
|
||||
return RGBA{}, err
|
||||
}
|
||||
c, err := parseFloatValue(parts[1])
|
||||
if err != nil {
|
||||
return RGBA{}, err
|
||||
}
|
||||
h, err := parseFloatValue(parts[2])
|
||||
if err != nil {
|
||||
return RGBA{}, err
|
||||
}
|
||||
|
||||
// Validate for NaN and infinity
|
||||
if math.IsNaN(l) || math.IsInf(l, 0) ||
|
||||
math.IsNaN(c) || math.IsInf(c, 0) ||
|
||||
math.IsNaN(h) || math.IsInf(h, 0) {
|
||||
return RGBA{}, errors.New("invalid float value")
|
||||
}
|
||||
|
||||
// Handle percentages for L
|
||||
if strings.Contains(parts[0], "%") {
|
||||
l /= 100.0
|
||||
}
|
||||
|
||||
// Clamp to reasonable ranges
|
||||
l = max(0.0, min(l, 1.0))
|
||||
c = max(0.0, c) // Chroma is unbounded
|
||||
h = math.Mod(h, 360) // Wrap hue to 0-360
|
||||
if h < 0 {
|
||||
h += 360
|
||||
}
|
||||
|
||||
// Convert OKLCH to sRGB with gamut mapping
|
||||
r, g, b := oklchToSrgbGamutMap(l, c, h)
|
||||
return RGBA{as8bit(r), as8bit(g), as8bit(b), 0}, nil
|
||||
}
|
||||
|
||||
func as8bit(x float64) uint8 { return uint8(math.Round(x * 255)) }
|
||||
|
||||
// parseLab parses LAB color: lab(l a b) or lab(l, a, b)
|
||||
func parseLab(spec string) (RGBA, error) {
|
||||
spec = strings.TrimRight(spec, ")")
|
||||
parts := splitColorComponents(spec)
|
||||
|
||||
if len(parts) != 3 {
|
||||
return RGBA{}, errors.New("not enough parts")
|
||||
}
|
||||
|
||||
l, err := parseFloatValue(parts[0])
|
||||
if err != nil {
|
||||
return RGBA{}, err
|
||||
}
|
||||
a, err := parseFloatValue(parts[1])
|
||||
if err != nil {
|
||||
return RGBA{}, err
|
||||
}
|
||||
b, err := parseFloatValue(parts[2])
|
||||
if err != nil {
|
||||
return RGBA{}, err
|
||||
}
|
||||
|
||||
// Validate for NaN and infinity
|
||||
if math.IsNaN(l) || math.IsInf(l, 0) ||
|
||||
math.IsNaN(a) || math.IsInf(a, 0) ||
|
||||
math.IsNaN(b) || math.IsInf(b, 0) {
|
||||
return RGBA{}, errors.New("invalid float value")
|
||||
}
|
||||
|
||||
// Clamp L to 0-100
|
||||
l = max(0.0, min(l, 100.0))
|
||||
|
||||
// Convert LAB to OKLCH, then use gamut mapping to sRGB
|
||||
lOk, c, h := labToOklch(l, a, b)
|
||||
|
||||
// Apply gamut mapping in OKLCH space
|
||||
r, g, bVal := oklchToSrgbGamutMap(lOk, c, h)
|
||||
return RGBA{as8bit(r), as8bit(g), as8bit(bVal), 0}, nil
|
||||
}
|
||||
|
||||
// splitColorComponents splits color components by comma or whitespace
|
||||
func splitColorComponents(spec string) []string {
|
||||
re := regexp.MustCompile(`[,\s]+`)
|
||||
parts := re.Split(spec, -1)
|
||||
|
||||
var result []string
|
||||
for _, part := range parts {
|
||||
part = strings.TrimSpace(part)
|
||||
part = strings.TrimRight(part, "%,")
|
||||
if part != "" {
|
||||
result = append(result, part)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// parseFloatValue parses a float value, handling percentages
|
||||
func parseFloatValue(s string) (float64, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
s = strings.TrimRight(s, "%,")
|
||||
return strconv.ParseFloat(s, 64)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// License: GPLv3 Copyright: 2025, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package style
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Benchmark color parsing functions to demonstrate performance
|
||||
|
||||
func BenchmarkParseOklch(b *testing.B) {
|
||||
for b.Loop() {
|
||||
_, _ = parseOklch("0.5 0.1 180")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseLab(b *testing.B) {
|
||||
for b.Loop() {
|
||||
_, _ = parseLab("50 0 0")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseColorHex(b *testing.B) {
|
||||
for b.Loop() {
|
||||
_, _ = ParseColor("#ff0000")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseColorOklch(b *testing.B) {
|
||||
for b.Loop() {
|
||||
_, _ = ParseColor("oklch(0.5 0.1 180)")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseColorLab(b *testing.B) {
|
||||
for b.Loop() {
|
||||
_, _ = ParseColor("lab(50 0 0)")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseColorWithComment(b *testing.B) {
|
||||
for b.Loop() {
|
||||
_, _ = ParseColor("oklch(0.5 0.1 180) # vibrant color")
|
||||
}
|
||||
}
|
||||
|
||||
// Benchmark the gamut mapping algorithm specifically
|
||||
func BenchmarkOklchToSrgbGamutMap(b *testing.B) {
|
||||
for b.Loop() {
|
||||
oklchToSrgbGamutMap(0.7, 0.4, 25) // Very saturated color requiring gamut mapping
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkOklchToSrgbGamutMapInGamut(b *testing.B) {
|
||||
for b.Loop() {
|
||||
oklchToSrgbGamutMap(0.5, 0.05, 180) // Already in gamut
|
||||
}
|
||||
}
|
||||
|
||||
// Benchmark parsing many colors (simulating config file parsing)
|
||||
func BenchmarkParseManyColors(b *testing.B) {
|
||||
colors := []string{
|
||||
"#ff0000",
|
||||
"#00ff00",
|
||||
"#0000ff",
|
||||
"oklch(0.5 0.1 180)",
|
||||
"lab(50 20 -30)",
|
||||
"rgb:ff/00/00",
|
||||
"red",
|
||||
"blue",
|
||||
"green",
|
||||
}
|
||||
|
||||
for b.Loop() {
|
||||
for _, color := range colors {
|
||||
_, _ = ParseColor(color)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// License: GPLv3 Copyright: 2025, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package style
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseColor(t *testing.T) {
|
||||
type tr struct {
|
||||
input string
|
||||
expected RGBA
|
||||
}
|
||||
c := func(t string, r, g, b uint8) tr { return tr{t, RGBA{r, g, b, 0}} }
|
||||
tests := []tr{
|
||||
c(`#eee # comment`, 0xee, 0xee, 0xee),
|
||||
c(`#234567`, 0x23, 0x45, 0x67),
|
||||
c(`#abcabcdef`, 0xab, 0xab, 0xde),
|
||||
c(`rgb:e/e/e # comment`, 0xee, 0xee, 0xee),
|
||||
c(`rgb:23/45/67`, 0x23, 0x45, 0x67),
|
||||
c(`rgb:abc/abc/def`, 0xab, 0xab, 0xde),
|
||||
c(`red`, 0xff, 0, 0),
|
||||
c(`alice blue # comment`, 240, 248, 255),
|
||||
c(`oklch(1,0,0)`, 255, 255, 255),
|
||||
c(`oklch(0,0,0)`, 0, 0, 0),
|
||||
c(`oklch(0.5,0.1,180)`, 0, 117, 101),
|
||||
c(`oklch(0.7 0.15 140) # comment`, 0x68, 0xb4, 0x57),
|
||||
c(`oklch(0.9 0.05 265)`, 0xce, 0xde, 0xff),
|
||||
c(`lab(70 50 -30)`, 0xea, 0x88, 0xe2),
|
||||
c(`lab(50,0,0)`, 199, 199, 199),
|
||||
c(`lab(100,0,0)`, 255, 255, 255),
|
||||
c(`lab(0,0,0)`, 0, 0, 0),
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.input, func(t *testing.T) {
|
||||
actual, err := ParseColor(tt.input)
|
||||
if actual != tt.expected {
|
||||
t.Errorf("ParseColor(%#v) error = %v, got %v wanted %v", tt.input, err, actual, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package style
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
type sgr_color struct {
|
||||
number int
|
||||
color RGBA
|
||||
}
|
||||
|
||||
func (self sgr_color) as_sgr(base int) string {
|
||||
if self.number == 0 {
|
||||
return ""
|
||||
}
|
||||
if self.number > 0 {
|
||||
n := self.number - 1
|
||||
if n <= 15 && (base == 30 || base == 40) {
|
||||
if n <= 7 {
|
||||
return strconv.Itoa(base + n)
|
||||
}
|
||||
return strconv.Itoa(base + 60 + n - 7)
|
||||
}
|
||||
return fmt.Sprintf("%d:5:%d", base+8, n)
|
||||
}
|
||||
return fmt.Sprintf("%d:2:%d:%d:%d", base+8, self.color.Red, self.color.Green, self.color.Blue)
|
||||
}
|
||||
|
||||
func as_uint8(x int) uint8 {
|
||||
return uint8(uint(x) & 0xff)
|
||||
}
|
||||
|
||||
func (self *sgr_color) from_extended(nums []int) bool {
|
||||
switch nums[0] {
|
||||
case 5:
|
||||
if len(nums) > 1 {
|
||||
self.number = 1 + nums[1]
|
||||
return true
|
||||
}
|
||||
case 2:
|
||||
if len(nums) > 3 {
|
||||
self.number = -1
|
||||
self.color.Red = as_uint8(nums[1])
|
||||
self.color.Green = as_uint8(nums[2])
|
||||
self.color.Blue = as_uint8(nums[3])
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type sgr_state struct {
|
||||
italic, reverse, bold, dim, strikethrough bool
|
||||
underline_style underline_style
|
||||
fg, bg, uc sgr_color
|
||||
}
|
||||
|
||||
func (self *sgr_state) reset() {
|
||||
*self = sgr_state{}
|
||||
}
|
||||
|
||||
func (self sgr_state) as_sgr(for_close bool) string {
|
||||
ans := make([]byte, 0, 32)
|
||||
if for_close {
|
||||
if self.bold {
|
||||
ans = append(ans, "221;"...)
|
||||
}
|
||||
if self.dim {
|
||||
ans = append(ans, "222;"...)
|
||||
}
|
||||
if self.italic {
|
||||
ans = append(ans, "23;"...)
|
||||
}
|
||||
if self.reverse {
|
||||
ans = append(ans, "27;"...)
|
||||
}
|
||||
if self.strikethrough {
|
||||
ans = append(ans, "29;"...)
|
||||
}
|
||||
if self.underline_style != no_underline && self.underline_style != nil_underline {
|
||||
ans = append(ans, "4:0;"...)
|
||||
}
|
||||
if self.fg.number != 0 {
|
||||
ans = append(ans, "39;"...)
|
||||
}
|
||||
if self.bg.number != 0 {
|
||||
ans = append(ans, "49;"...)
|
||||
}
|
||||
if self.uc.number != 0 {
|
||||
ans = append(ans, "59;"...)
|
||||
}
|
||||
} else {
|
||||
if self.bold {
|
||||
ans = append(ans, "1;"...)
|
||||
}
|
||||
if self.dim {
|
||||
ans = append(ans, "2;"...)
|
||||
}
|
||||
if self.italic {
|
||||
ans = append(ans, "3;"...)
|
||||
}
|
||||
if self.reverse {
|
||||
ans = append(ans, "7;"...)
|
||||
}
|
||||
if self.strikethrough {
|
||||
ans = append(ans, "9;"...)
|
||||
}
|
||||
if self.underline_style != no_underline && self.underline_style != nil_underline {
|
||||
ans = append(ans, fmt.Sprintf("4:%d;", self.underline_style)...)
|
||||
}
|
||||
if q := self.fg.as_sgr(30); q != "" {
|
||||
ans = append(ans, q...)
|
||||
ans = append(ans, ';')
|
||||
}
|
||||
if q := self.bg.as_sgr(40); q != "" {
|
||||
ans = append(ans, q...)
|
||||
ans = append(ans, ';')
|
||||
}
|
||||
if q := self.uc.as_sgr(50); q != "" {
|
||||
ans = append(ans, q...)
|
||||
ans = append(ans, ';')
|
||||
}
|
||||
}
|
||||
if len(ans) > 0 {
|
||||
ans = ans[:len(ans)-1]
|
||||
}
|
||||
return utils.UnsafeBytesToString(ans)
|
||||
}
|
||||
|
||||
func (self sgr_state) as_escape_codes(for_close bool) string {
|
||||
q := self.as_sgr(for_close)
|
||||
if q == "" {
|
||||
return q
|
||||
}
|
||||
return fmt.Sprintf("\x1b[%sm", q)
|
||||
}
|
||||
|
||||
func (self *sgr_state) apply_csi(raw string) {
|
||||
if !strings.HasSuffix(raw, "m") {
|
||||
return
|
||||
}
|
||||
raw = raw[:len(raw)-1]
|
||||
if raw == "" {
|
||||
raw = "0"
|
||||
}
|
||||
parts := strings.Split(raw, ";")
|
||||
nums := make([]int, 0, 8)
|
||||
for _, part := range parts {
|
||||
subparts := strings.Split(part, ":")
|
||||
nums = nums[:0]
|
||||
for _, b := range subparts {
|
||||
q, err := strconv.Atoi(b)
|
||||
if err == nil {
|
||||
nums = append(nums, q)
|
||||
}
|
||||
}
|
||||
if len(nums) == 0 {
|
||||
continue
|
||||
}
|
||||
switch nums[0] {
|
||||
case 0:
|
||||
self.reset()
|
||||
case 1:
|
||||
self.dim, self.bold = false, true
|
||||
case 221:
|
||||
self.bold = false
|
||||
case 2:
|
||||
self.dim, self.bold = true, false
|
||||
case 222:
|
||||
self.dim = false
|
||||
case 22:
|
||||
self.dim, self.bold = false, false
|
||||
case 3:
|
||||
self.italic = true
|
||||
case 23:
|
||||
self.italic = false
|
||||
case 7:
|
||||
self.reverse = true
|
||||
case 27:
|
||||
self.reverse = false
|
||||
case 9:
|
||||
self.strikethrough = true
|
||||
case 29:
|
||||
self.strikethrough = false
|
||||
case 24:
|
||||
self.underline_style = no_underline
|
||||
case 4:
|
||||
us := 1
|
||||
if len(nums) > 1 {
|
||||
us = nums[1]
|
||||
}
|
||||
switch us {
|
||||
case 0:
|
||||
self.underline_style = no_underline
|
||||
case 1:
|
||||
self.underline_style = straight_underline
|
||||
case 2:
|
||||
self.underline_style = double_underline
|
||||
case 3:
|
||||
self.underline_style = curly_underline
|
||||
case 4:
|
||||
self.underline_style = dotted_underline
|
||||
case 5:
|
||||
self.underline_style = dashed_underline
|
||||
}
|
||||
case 30, 31, 32, 33, 34, 35, 36, 37:
|
||||
self.fg.number = nums[0] + 1 - 30
|
||||
case 90, 91, 92, 93, 94, 95, 96, 97:
|
||||
self.fg.number = nums[0] + 1 - 82
|
||||
case 38:
|
||||
self.fg.from_extended(nums[1:])
|
||||
case 39:
|
||||
self.fg.number = 0
|
||||
case 40, 41, 42, 43, 44, 45, 46, 47:
|
||||
self.bg.number = nums[0] + 1 - 40
|
||||
case 100, 101, 102, 103, 104, 105, 106, 107:
|
||||
self.bg.number = nums[0] + 1 - 92
|
||||
case 48:
|
||||
self.bg.from_extended(nums[1:])
|
||||
case 49:
|
||||
self.bg.number = 0
|
||||
case 58:
|
||||
self.uc.from_extended(nums[1:])
|
||||
case 59:
|
||||
self.uc.number = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type hyperlink_state struct {
|
||||
id, url string
|
||||
}
|
||||
|
||||
func (self *hyperlink_state) apply_osc(raw string) {
|
||||
parts := strings.SplitN(raw, ";", 3)
|
||||
if len(parts) != 3 || parts[0] != "8" {
|
||||
return
|
||||
}
|
||||
self.id = parts[1]
|
||||
self.url = parts[2]
|
||||
}
|
||||
|
||||
func (self *hyperlink_state) reset() {
|
||||
self.id = ""
|
||||
self.url = ""
|
||||
}
|
||||
|
||||
func (self hyperlink_state) as_escape_codes(for_close bool) string {
|
||||
if self.id == "" && self.url == "" {
|
||||
return ""
|
||||
}
|
||||
if for_close {
|
||||
return "\x1b]8;;\x1b\\"
|
||||
}
|
||||
return fmt.Sprintf("\x1b]8;%s;%s\x1b\\", self.id, self.url)
|
||||
}
|
||||
|
||||
type line_builder struct {
|
||||
buf []byte
|
||||
cursor_pos int
|
||||
seen_non_space_chars bool
|
||||
pos_of_trailing_whitespace int
|
||||
}
|
||||
|
||||
func (self *line_builder) reset(trim_whitespace bool) string {
|
||||
ans := string(self.buf)
|
||||
if trim_whitespace && self.pos_of_trailing_whitespace > -1 {
|
||||
prefix := ans[:self.pos_of_trailing_whitespace]
|
||||
tp := strings.TrimRightFunc(prefix, is_space)
|
||||
if len(tp) != len(prefix) {
|
||||
ans = tp + ans[self.pos_of_trailing_whitespace:]
|
||||
}
|
||||
|
||||
}
|
||||
self.buf = self.buf[:0]
|
||||
self.cursor_pos = 0
|
||||
self.seen_non_space_chars = false
|
||||
self.pos_of_trailing_whitespace = -1
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *line_builder) has_space_for_width(w, max_width int) bool {
|
||||
return w+self.cursor_pos <= max_width
|
||||
}
|
||||
|
||||
func (self *line_builder) add_space(ch rune, trim_whitespace bool) {
|
||||
if !trim_whitespace || self.seen_non_space_chars {
|
||||
self.buf = utf8.AppendRune(self.buf, ch)
|
||||
self.pos_of_trailing_whitespace = len(self.buf)
|
||||
self.cursor_pos += wcswidth.Runewidth(ch)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *line_builder) add_word(word []byte, width int) {
|
||||
self.seen_non_space_chars = true
|
||||
self.pos_of_trailing_whitespace = -1
|
||||
self.buf = append(self.buf, word...)
|
||||
self.cursor_pos += width
|
||||
}
|
||||
|
||||
func (self *line_builder) add_indent(word string, width int) {
|
||||
if word != "" {
|
||||
self.buf = append(self.buf, word...)
|
||||
self.cursor_pos += width
|
||||
}
|
||||
}
|
||||
|
||||
func (self *line_builder) add_escape_code(code string) {
|
||||
self.buf = append(self.buf, code...)
|
||||
}
|
||||
|
||||
func (self *line_builder) add_escape_code2(prefix string, body []byte, suffix string) {
|
||||
self.buf = append(self.buf, prefix...)
|
||||
self.buf = append(self.buf, body...)
|
||||
self.buf = append(self.buf, suffix...)
|
||||
}
|
||||
|
||||
type escape_code_ struct {
|
||||
prefix, body, suffix string
|
||||
}
|
||||
|
||||
type word_builder struct {
|
||||
buf []byte
|
||||
escape_codes []escape_code_
|
||||
text_start_position int
|
||||
wcswidth *wcswidth.WCWidthIterator
|
||||
}
|
||||
|
||||
func (self *word_builder) reset(copy_current_word func([]byte)) {
|
||||
copy_current_word(self.buf)
|
||||
self.buf = self.buf[:0]
|
||||
self.escape_codes = self.escape_codes[:0]
|
||||
self.text_start_position = 0
|
||||
self.wcswidth.Reset()
|
||||
}
|
||||
|
||||
func (self *word_builder) is_empty() bool {
|
||||
return len(self.buf) == 0
|
||||
}
|
||||
|
||||
func (self *word_builder) width() int {
|
||||
return self.wcswidth.CurrentWidth()
|
||||
}
|
||||
|
||||
func (self *word_builder) add_escape_code(prefix string, body []byte, suffix string) {
|
||||
e := escape_code_{prefix: prefix, body: string(body), suffix: suffix}
|
||||
self.escape_codes = append(self.escape_codes, e)
|
||||
self.buf = append(self.buf, prefix...)
|
||||
self.buf = append(self.buf, body...)
|
||||
self.buf = append(self.buf, suffix...)
|
||||
}
|
||||
|
||||
func (self *word_builder) has_text() bool { return self.text_start_position != 0 }
|
||||
|
||||
func (self *word_builder) recalculate_width() {
|
||||
self.wcswidth.Reset()
|
||||
self.wcswidth.Parse(self.buf)
|
||||
}
|
||||
|
||||
func (self *word_builder) add_rune(ch rune) (num_bytes_written int) {
|
||||
before := len(self.buf)
|
||||
self.buf = utf8.AppendRune(self.buf, ch)
|
||||
num_bytes_written = len(self.buf) - before
|
||||
for _, b := range self.buf[before:] {
|
||||
self.wcswidth.ParseByte(b)
|
||||
}
|
||||
if self.text_start_position == 0 {
|
||||
self.text_start_position = len(self.buf)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *word_builder) remove_trailing_bytes(n int) {
|
||||
self.buf = self.buf[:len(self.buf)-n]
|
||||
self.recalculate_width()
|
||||
}
|
||||
|
||||
type wrapper struct {
|
||||
ep wcswidth.EscapeCodeParser
|
||||
indent string
|
||||
width, indent_width int
|
||||
trim_whitespace bool
|
||||
|
||||
sgr sgr_state
|
||||
hyperlink hyperlink_state
|
||||
current_word word_builder
|
||||
current_line line_builder
|
||||
lines []string
|
||||
ignore_lines_containing []string
|
||||
}
|
||||
|
||||
func (self *wrapper) newline_prefix() {
|
||||
self.current_line.add_escape_code(self.sgr.as_escape_codes(true))
|
||||
self.current_line.add_escape_code(self.hyperlink.as_escape_codes(true))
|
||||
self.current_line.add_indent(self.indent, self.indent_width)
|
||||
self.current_line.add_escape_code(self.sgr.as_escape_codes(false))
|
||||
self.current_line.add_escape_code(self.hyperlink.as_escape_codes(false))
|
||||
}
|
||||
|
||||
func (self *wrapper) append_line(line string) {
|
||||
for _, q := range self.ignore_lines_containing {
|
||||
if strings.Contains(line, q) {
|
||||
return
|
||||
}
|
||||
}
|
||||
self.lines = append(self.lines, line)
|
||||
}
|
||||
|
||||
func (self *wrapper) end_current_line() {
|
||||
line := self.current_line.reset(self.trim_whitespace)
|
||||
if strings.HasSuffix(line, self.indent) && wcswidth.Stringwidth(line) == self.indent_width {
|
||||
line = line[:len(line)-len(self.indent)]
|
||||
}
|
||||
self.append_line(line)
|
||||
self.newline_prefix()
|
||||
}
|
||||
|
||||
func (self *wrapper) print_word() {
|
||||
w := self.current_word.width()
|
||||
if !self.current_line.has_space_for_width(w, self.width) {
|
||||
self.end_current_line()
|
||||
w = self.current_word.width()
|
||||
}
|
||||
for _, e := range self.current_word.escape_codes {
|
||||
if e.suffix != "" {
|
||||
self.hyperlink.apply_osc(e.body)
|
||||
} else {
|
||||
self.sgr.apply_csi(e.body)
|
||||
}
|
||||
}
|
||||
self.current_word.reset(func(word []byte) {
|
||||
self.current_line.add_word(word, w)
|
||||
})
|
||||
}
|
||||
|
||||
func is_space(ch rune) bool {
|
||||
return ch != 0xa0 && unicode.IsSpace(ch)
|
||||
}
|
||||
|
||||
func (self *wrapper) handle_rune(ch rune) error {
|
||||
if ch == '\n' {
|
||||
self.print_word()
|
||||
self.end_current_line()
|
||||
} else if is_space(ch) {
|
||||
if self.current_word.has_text() {
|
||||
self.print_word()
|
||||
}
|
||||
if self.current_line.cursor_pos >= self.width {
|
||||
self.end_current_line()
|
||||
}
|
||||
self.current_line.add_space(ch, self.trim_whitespace)
|
||||
} else {
|
||||
num_of_bytes_written := self.current_word.add_rune(ch)
|
||||
if self.current_word.width() > self.width {
|
||||
self.current_word.remove_trailing_bytes(num_of_bytes_written)
|
||||
self.print_word()
|
||||
return self.handle_rune(ch)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *wrapper) handle_csi(raw []byte) error {
|
||||
self.current_word.add_escape_code("\x1b[", raw, "")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *wrapper) handle_osc(raw []byte) error {
|
||||
self.current_word.add_escape_code("\x1b]", raw, "\x1b\\")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *wrapper) wrap_text(text string) []string {
|
||||
if text == "" {
|
||||
return []string{""}
|
||||
}
|
||||
self.current_line.reset(self.trim_whitespace)
|
||||
self.current_word.reset(func([]byte) {})
|
||||
self.lines = self.lines[:0]
|
||||
self.current_line.add_indent(self.indent, self.indent_width)
|
||||
self.ep.ParseString(text)
|
||||
if !self.current_word.is_empty() {
|
||||
self.print_word()
|
||||
}
|
||||
self.end_current_line()
|
||||
last_line := self.current_line.reset(self.trim_whitespace)
|
||||
self.newline_prefix()
|
||||
if last_line == self.current_line.reset(self.trim_whitespace) {
|
||||
last_line = ""
|
||||
}
|
||||
if last_line != "" {
|
||||
self.append_line(last_line)
|
||||
}
|
||||
return self.lines
|
||||
}
|
||||
|
||||
func new_wrapper(opts WrapOptions, width int) *wrapper {
|
||||
width = max(2, width)
|
||||
ans := wrapper{indent: opts.Indent, width: width, trim_whitespace: opts.Trim_whitespace, indent_width: wcswidth.Stringwidth(opts.Indent)}
|
||||
if opts.Ignore_lines_containing != "" {
|
||||
ans.ignore_lines_containing = utils.Splitlines(opts.Ignore_lines_containing)
|
||||
}
|
||||
ans.ep.HandleRune = ans.handle_rune
|
||||
ans.ep.HandleCSI = ans.handle_csi
|
||||
ans.ep.HandleOSC = ans.handle_osc
|
||||
ans.lines = make([]string, 0, 32)
|
||||
ans.current_word.escape_codes = make([]escape_code_, 0, 8)
|
||||
ans.current_word.wcswidth = wcswidth.CreateWCWidthIterator()
|
||||
return &ans
|
||||
}
|
||||
|
||||
type WrapOptions struct {
|
||||
Ignore_lines_containing string
|
||||
Trim_whitespace bool // trim whitespace at the start and end of lines (start is after indent).
|
||||
Indent string // indent to add at the start of every line all formatting is cleared for the indent.
|
||||
}
|
||||
|
||||
func WrapTextAsLines(text string, width int, opts WrapOptions) []string {
|
||||
w := new_wrapper(opts, width)
|
||||
return w.wrap_text(text)
|
||||
}
|
||||
|
||||
func WrapText(text string, width int, opts WrapOptions) string {
|
||||
return strings.Join(WrapTextAsLines(text, width, opts), "\n")
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package style
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFormatWithIndent(t *testing.T) {
|
||||
|
||||
screen_width := 0
|
||||
opts := WrapOptions{}
|
||||
|
||||
tx := func(text string, expected ...string) {
|
||||
q := opts.Indent + strings.Join(expected, "")
|
||||
actual := WrapText(text, screen_width, opts)
|
||||
if actual != q {
|
||||
os, _ := json.Marshal(opts)
|
||||
t.Fatalf("\nFailed for: %#v\nOptions: %s\nexpected: %#v\nactual: %#v", text, os, q, actual)
|
||||
}
|
||||
}
|
||||
|
||||
opts.Indent = ""
|
||||
screen_width = 4
|
||||
tx("one two", "one \ntwo")
|
||||
tx("a b", "a b")
|
||||
screen_width = 3
|
||||
tx("one tw", "one\n tw")
|
||||
|
||||
screen_width = 4
|
||||
opts.Trim_whitespace = true
|
||||
opts.Indent = "X"
|
||||
tx("one two", "one\nXtwo")
|
||||
tx("\x1b[2mone \x1b[mtwo", "\x1b[2mone\n\x1b[222mX\x1b[2m\x1b[mtwo")
|
||||
screen_width = 3
|
||||
tx("on tw", "on\nXtw")
|
||||
opts.Indent = ""
|
||||
opts.Trim_whitespace = false
|
||||
|
||||
opts.Indent = "__"
|
||||
screen_width = 11
|
||||
tx("testing\n\ntwo", "testing\n\n__two")
|
||||
tx("testing\n \ntwo", "testing\n__ \n__two")
|
||||
a := strings.Repeat("a", screen_width-len(opts.Indent)-1)
|
||||
tx(a+" b", a+" \n__b")
|
||||
|
||||
tx("123456 \x1b[31m789a", "123456 \n__\x1b[31m789a")
|
||||
tx("12 \x1b[31m789 abcd", "12 \x1b[31m789 \n\x1b[39m__\x1b[31mabcd")
|
||||
tx("bb \x1b]8;;http://xyz.com\x1b\\text\x1b]8;;\x1b\\ two", "bb \x1b]8;;http://xyz.com\x1b\\text\x1b]8;;\x1b\\ \n__two")
|
||||
tx("\x1b[31maaaaaa \x1b[39mbbbbbb", "\x1b[31maaaaaa \n\x1b[39m__\x1b[31m\x1b[39mbbbbbb")
|
||||
tx(
|
||||
"\x1b[31;4:3m\x1b]8;;XXX\x1b\\combined using\x1b]8;;\x1b\\ operators",
|
||||
"\x1b[31;4:3m\x1b]8;;XXX\x1b\\combined \n\x1b[4:0;39m\x1b]8;;\x1b\\__\x1b[4:3;31m\x1b]8;;XXX\x1b\\using\x1b]8;;\x1b\\ \n\x1b[4:0;39m__\x1b[4:3;31moperators")
|
||||
|
||||
opts.Indent = ""
|
||||
screen_width = 3
|
||||
tx("one", "one")
|
||||
tx("four", "fou\nr")
|
||||
tx("nl\n\n", "nl\n\n")
|
||||
tx("four\n\n", "fou\nr\n\n")
|
||||
|
||||
screen_width = 8
|
||||
tx(
|
||||
"\x1b[1mbold\x1b[221m no more bold",
|
||||
"\x1b[1mbold\x1b[221m no \nmore \nbold",
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package style
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils/shlex"
|
||||
)
|
||||
|
||||
type escape_code interface {
|
||||
prefix() string
|
||||
suffix() string
|
||||
is_empty() bool
|
||||
}
|
||||
|
||||
// bool values {{{
|
||||
type bool_value struct {
|
||||
is_set, val bool
|
||||
}
|
||||
|
||||
func (self bool_value) as_sgr(start, end string, prefix, suffix []string) ([]string, []string) {
|
||||
if self.is_set {
|
||||
if !self.val {
|
||||
start, end = end, start
|
||||
}
|
||||
prefix = append(prefix, start)
|
||||
suffix = append(suffix, end)
|
||||
}
|
||||
return prefix, suffix
|
||||
}
|
||||
|
||||
func (self *bool_value) set_val(val bool) {
|
||||
self.is_set = true
|
||||
self.val = val
|
||||
}
|
||||
|
||||
func (self *bool_value) from_string(raw string) bool {
|
||||
switch strings.ToLower(raw) {
|
||||
case "y", "yes", "true", "1":
|
||||
self.set_val(true)
|
||||
return true
|
||||
case "n", "no", "false", "0":
|
||||
self.set_val(false)
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// }}}
|
||||
|
||||
// color values {{{
|
||||
type RGBA struct {
|
||||
Red, Green, Blue, Inverse_alpha uint8
|
||||
}
|
||||
|
||||
func (self RGBA) AsRGBSharp() string {
|
||||
return fmt.Sprintf("#%02x%02x%02x", self.Red, self.Green, self.Blue)
|
||||
}
|
||||
|
||||
func (self *RGBA) parse_rgb_strings(r string, g string, b string) bool {
|
||||
var rv, gv, bv uint64
|
||||
var err error
|
||||
if len(r) == 1 {
|
||||
r += r
|
||||
g += g
|
||||
b += b
|
||||
}
|
||||
if rv, err = strconv.ParseUint(r[:min(len(r), 2)], 16, 8); err != nil {
|
||||
return false
|
||||
}
|
||||
if gv, err = strconv.ParseUint(g[:min(len(r), 2)], 16, 8); err != nil {
|
||||
return false
|
||||
}
|
||||
if bv, err = strconv.ParseUint(b[:min(len(r), 2)], 16, 8); err != nil {
|
||||
return false
|
||||
}
|
||||
self.Red, self.Green, self.Blue = uint8(rv), uint8(gv), uint8(bv)
|
||||
return true
|
||||
}
|
||||
|
||||
func fas_uint8(x float64) uint8 {
|
||||
x = max(0, min(x, 1))
|
||||
return uint8(x * 255)
|
||||
}
|
||||
|
||||
func (self *RGBA) parse_rgb_intensities(r string, g string, b string) bool {
|
||||
var rv, gv, bv float64
|
||||
var err error
|
||||
if rv, err = strconv.ParseFloat(r, 64); err != nil {
|
||||
return false
|
||||
}
|
||||
if gv, err = strconv.ParseFloat(g, 64); err != nil {
|
||||
return false
|
||||
}
|
||||
if bv, err = strconv.ParseFloat(b, 64); err != nil {
|
||||
return false
|
||||
}
|
||||
self.Red, self.Green, self.Blue = fas_uint8(rv), fas_uint8(gv), fas_uint8(bv)
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *RGBA) AsRGB() uint32 {
|
||||
return uint32(self.Blue) | (uint32(self.Green) << 8) | (uint32(self.Red) << 16)
|
||||
}
|
||||
|
||||
func (self *RGBA) IsDark() bool {
|
||||
return self.Red < 155 && self.Green < 155 && self.Blue < 155
|
||||
}
|
||||
|
||||
func (self *RGBA) FromRGB(col uint32) {
|
||||
self.Red = uint8((col >> 16) & 0xff)
|
||||
self.Green = uint8((col >> 8) & 0xff)
|
||||
self.Blue = uint8((col) & 0xff)
|
||||
}
|
||||
|
||||
type color_type struct {
|
||||
is_numbered bool
|
||||
val RGBA
|
||||
}
|
||||
|
||||
func (self color_type) as_sgr(number_base int, prefix, suffix []string) ([]string, []string) {
|
||||
suffix = append(suffix, strconv.Itoa(number_base+9))
|
||||
if self.is_numbered {
|
||||
num := int(self.val.Red)
|
||||
if num < 16 && number_base < 50 {
|
||||
if num > 7 {
|
||||
number_base += 60
|
||||
num -= 8
|
||||
}
|
||||
prefix = append(prefix, strconv.Itoa(number_base+num))
|
||||
} else {
|
||||
prefix = append(prefix, fmt.Sprintf("%d:5:%d", number_base+8, num))
|
||||
}
|
||||
} else {
|
||||
prefix = append(prefix, fmt.Sprintf("%d:2:%d:%d:%d", number_base+8, self.val.Red, self.val.Green, self.val.Blue))
|
||||
}
|
||||
return prefix, suffix
|
||||
}
|
||||
|
||||
type color_value struct {
|
||||
is_set bool
|
||||
val color_type
|
||||
}
|
||||
|
||||
func parse_sharp(color string) (ans RGBA, err error) {
|
||||
if len(color)%3 != 0 {
|
||||
return RGBA{}, fmt.Errorf("length not a multiple of 3")
|
||||
}
|
||||
part_size := len(color) / 3
|
||||
r, g, b := color[:part_size], color[part_size:2*part_size], color[part_size*2:part_size*3]
|
||||
if !ans.parse_rgb_strings(r, g, b) {
|
||||
err = fmt.Errorf("invalid rgb numbers")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func parse_rgb(color string) (ans RGBA, err error) {
|
||||
colors := strings.Split(color, "/")
|
||||
if len(colors) != 3 {
|
||||
return RGBA{}, fmt.Errorf("length not a multiple of 3")
|
||||
}
|
||||
if ans.parse_rgb_strings(colors[0], colors[1], colors[2]) {
|
||||
return
|
||||
}
|
||||
err = fmt.Errorf("invalid rgb numbers")
|
||||
return
|
||||
}
|
||||
|
||||
func parse_rgbi(color string) (ans RGBA, err error) {
|
||||
colors := strings.Split(color, "/")
|
||||
if len(colors) != 3 {
|
||||
return RGBA{}, fmt.Errorf("length not a multiple of 3")
|
||||
}
|
||||
if ans.parse_rgb_intensities(colors[0], colors[1], colors[2]) {
|
||||
return
|
||||
}
|
||||
err = fmt.Errorf("invalid rgb numbers")
|
||||
return
|
||||
}
|
||||
|
||||
func ParseColor(color string) (ans RGBA, err error) {
|
||||
// Strip inline comments (e.g., "oklch(...) # comment")
|
||||
// For hex colors like "#ff0000", preserve the first #, but strip comments after spaces
|
||||
color = strings.TrimSpace(color)
|
||||
if strings.HasPrefix(color, "#") {
|
||||
// For hex colors, only strip comments after whitespace
|
||||
parts := strings.Fields(color)
|
||||
if len(parts) > 0 {
|
||||
color = parts[0] // Keep only the hex color part
|
||||
}
|
||||
} else {
|
||||
// For non-hex colors, strip everything after #
|
||||
if idx := strings.Index(color, "#"); idx >= 0 {
|
||||
color = strings.TrimSpace(color[:idx])
|
||||
}
|
||||
}
|
||||
|
||||
raw := strings.TrimSpace(strings.ToLower(color))
|
||||
if val, ok := ColorNames[raw]; ok {
|
||||
return val, nil
|
||||
}
|
||||
if len(raw) < 4 {
|
||||
return RGBA{}, fmt.Errorf("not a valid color name: %#v", color)
|
||||
}
|
||||
var parser func(string) (RGBA, error)
|
||||
switch raw[0] {
|
||||
case '#':
|
||||
parser = parse_sharp
|
||||
raw = raw[1:]
|
||||
case 'o':
|
||||
if strings.HasPrefix(raw, "oklch(") {
|
||||
parser, raw = parseOklch, raw[6:]
|
||||
}
|
||||
case 'l':
|
||||
if strings.HasPrefix(raw, "lab(") {
|
||||
parser, raw = parseLab, raw[4:]
|
||||
}
|
||||
case 'r':
|
||||
if len(raw) > 4 && strings.HasPrefix(raw, "rgb") {
|
||||
raw = raw[3:]
|
||||
switch raw[0] {
|
||||
case ':':
|
||||
parser, raw = parse_rgb, raw[1:]
|
||||
case 'i':
|
||||
if strings.HasPrefix(raw, "i:") {
|
||||
parser, raw = parse_rgbi, raw[2:]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if parser == nil {
|
||||
err = fmt.Errorf("not a valid color name: %#v", color)
|
||||
} else {
|
||||
if ans, err = parser(raw); err != nil {
|
||||
err = fmt.Errorf("not a valid color name: %#v %w", color, err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type NullableColor struct {
|
||||
Color RGBA
|
||||
IsSet bool
|
||||
}
|
||||
|
||||
func ParseColorOrNone(color string) (NullableColor, error) {
|
||||
raw := strings.TrimSpace(strings.ToLower(color))
|
||||
if raw == "none" {
|
||||
return NullableColor{}, nil
|
||||
}
|
||||
c, err := ParseColor(raw)
|
||||
return NullableColor{Color: c, IsSet: err == nil}, err
|
||||
}
|
||||
|
||||
var named_colors = map[string]uint8{
|
||||
"black": 0, "red": 1, "green": 2, "yellow": 3, "blue": 4, "magenta": 5, "cyan": 6, "gray": 7, "white": 7,
|
||||
|
||||
"hi-black": 8, "hi-red": 9, "hi-green": 10, "hi-yellow": 11, "hi-blue": 12, "hi-magenta": 13, "hi-cyan": 14, "hi-gray": 15, "hi-white": 15,
|
||||
|
||||
"bright-black": 8, "bright-red": 9, "bright-green": 10, "bright-yellow": 11, "bright-blue": 12, "bright-magenta": 13, "bright-cyan": 14, "bright-gray": 15, "bright-white": 15,
|
||||
|
||||
"intense-black": 8, "intense-red": 9, "intense-green": 10, "intense-yellow": 11, "intense-blue": 12, "intense-magenta": 13, "intense-cyan": 14, "intense-gray": 15, "intense-white": 15,
|
||||
}
|
||||
|
||||
func (self *color_value) from_string(raw string) bool {
|
||||
if n, ok := named_colors[raw]; ok {
|
||||
self.is_set = true
|
||||
self.val = color_type{val: RGBA{Red: n}, is_numbered: true}
|
||||
return true
|
||||
}
|
||||
a, err := strconv.Atoi(raw)
|
||||
if err == nil && 0 <= a && a <= 255 {
|
||||
self.is_set = true
|
||||
self.val = color_type{val: RGBA{Red: uint8(a)}, is_numbered: true}
|
||||
return true
|
||||
}
|
||||
c, err := ParseColor(raw)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
self.is_set = true
|
||||
self.val = color_type{val: c}
|
||||
return true
|
||||
}
|
||||
|
||||
func (self color_value) as_sgr(number_base int, prefix, suffix []string) ([]string, []string) {
|
||||
if self.is_set {
|
||||
prefix, suffix = self.val.as_sgr(number_base, prefix, suffix)
|
||||
}
|
||||
return prefix, suffix
|
||||
}
|
||||
|
||||
// }}}
|
||||
|
||||
// underline values {{{
|
||||
type underline_style uint8
|
||||
|
||||
const (
|
||||
no_underline underline_style = 0
|
||||
straight_underline underline_style = 1
|
||||
double_underline underline_style = 2
|
||||
curly_underline underline_style = 3
|
||||
dotted_underline underline_style = 4
|
||||
dashed_underline underline_style = 5
|
||||
|
||||
nil_underline underline_style = 255
|
||||
)
|
||||
|
||||
type underline_value struct {
|
||||
is_set bool
|
||||
style underline_style
|
||||
}
|
||||
|
||||
func (self *underline_value) from_string(val string) bool {
|
||||
ans := nil_underline
|
||||
switch val {
|
||||
case "true", "yes", "y", "straight", "single":
|
||||
ans = straight_underline
|
||||
case "false", "no", "n", "none":
|
||||
ans = no_underline
|
||||
case "double":
|
||||
ans = double_underline
|
||||
case "curly":
|
||||
ans = curly_underline
|
||||
case "dotted":
|
||||
ans = dotted_underline
|
||||
case "dashed":
|
||||
ans = dashed_underline
|
||||
}
|
||||
if ans == nil_underline {
|
||||
return false
|
||||
}
|
||||
self.is_set = true
|
||||
self.style = ans
|
||||
return true
|
||||
}
|
||||
|
||||
func (self underline_value) as_sgr(prefix, suffix []string) ([]string, []string) {
|
||||
if self.is_set {
|
||||
s, e := "4:0", "4:0"
|
||||
if self.style != no_underline {
|
||||
s = "4:" + strconv.Itoa(int(self.style))
|
||||
}
|
||||
prefix = append(prefix, s)
|
||||
suffix = append(suffix, e)
|
||||
}
|
||||
return prefix, suffix
|
||||
}
|
||||
|
||||
// }}}
|
||||
|
||||
type sgr_code struct {
|
||||
bold, italic, reverse, dim, strikethrough bool_value
|
||||
fg, bg, uc color_value
|
||||
underline underline_value
|
||||
|
||||
_prefix, _suffix string
|
||||
}
|
||||
|
||||
func (self sgr_code) prefix() string {
|
||||
return self._prefix
|
||||
}
|
||||
|
||||
func (self sgr_code) suffix() string {
|
||||
return self._suffix
|
||||
}
|
||||
|
||||
func (self sgr_code) is_empty() bool {
|
||||
return self._prefix == ""
|
||||
}
|
||||
|
||||
type url_code struct {
|
||||
url string
|
||||
}
|
||||
|
||||
func (self url_code) prefix() string {
|
||||
return fmt.Sprintf("\x1b]8;;%s\x1b\\", self.url)
|
||||
}
|
||||
|
||||
func (self url_code) suffix() string {
|
||||
return "\x1b]8;;\x1b\\"
|
||||
}
|
||||
|
||||
func (self url_code) is_empty() bool {
|
||||
return self.url == ""
|
||||
}
|
||||
|
||||
func (self *sgr_code) update() {
|
||||
p := make([]string, 0, 1)
|
||||
s := make([]string, 0, 1)
|
||||
p, s = self.bold.as_sgr("1", "221", p, s)
|
||||
p, s = self.dim.as_sgr("2", "222", p, s)
|
||||
p, s = self.italic.as_sgr("3", "23", p, s)
|
||||
p, s = self.reverse.as_sgr("7", "27", p, s)
|
||||
p, s = self.strikethrough.as_sgr("9", "29", p, s)
|
||||
p, s = self.underline.as_sgr(p, s)
|
||||
p, s = self.fg.as_sgr(30, p, s)
|
||||
p, s = self.bg.as_sgr(40, p, s)
|
||||
p, s = self.uc.as_sgr(50, p, s)
|
||||
if len(p) > 0 {
|
||||
self._prefix = "\x1b[" + strings.Join(p, ";") + "m"
|
||||
} else {
|
||||
self._prefix = ""
|
||||
}
|
||||
if len(s) > 0 {
|
||||
self._suffix = "\x1b[" + strings.Join(s, ";") + "m"
|
||||
} else {
|
||||
self._suffix = ""
|
||||
}
|
||||
}
|
||||
|
||||
func parse_spec(spec string) []escape_code {
|
||||
ans := make([]escape_code, 0, 1)
|
||||
sgr := sgr_code{}
|
||||
sparts, _ := shlex.Split(spec)
|
||||
for _, p := range sparts {
|
||||
key, val, found := strings.Cut(p, "=")
|
||||
if !found {
|
||||
val = "true"
|
||||
}
|
||||
switch key {
|
||||
case "fg":
|
||||
sgr.fg.from_string(val)
|
||||
case "bg":
|
||||
sgr.bg.from_string(val)
|
||||
case "bold", "b":
|
||||
sgr.bold.from_string(val)
|
||||
case "italic", "i":
|
||||
sgr.italic.from_string(val)
|
||||
case "reverse":
|
||||
sgr.reverse.from_string(val)
|
||||
case "dim", "faint":
|
||||
sgr.dim.from_string(val)
|
||||
case "underline", "u":
|
||||
sgr.underline.from_string(val)
|
||||
case "strikethrough", "s":
|
||||
sgr.strikethrough.from_string(val)
|
||||
case "ucol", "underline_color", "uc":
|
||||
sgr.uc.from_string(val)
|
||||
}
|
||||
}
|
||||
sgr.update()
|
||||
if !sgr.is_empty() {
|
||||
ans = append(ans, &sgr)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
var parsed_spec_cache = make(map[string][]escape_code)
|
||||
var parsed_spec_cache_mutex = sync.Mutex{}
|
||||
|
||||
func cached_parse_spec(spec string) []escape_code {
|
||||
parsed_spec_cache_mutex.Lock()
|
||||
defer parsed_spec_cache_mutex.Unlock()
|
||||
if val, ok := parsed_spec_cache[spec]; ok {
|
||||
return val
|
||||
}
|
||||
ans := parse_spec(spec)
|
||||
parsed_spec_cache[spec] = ans
|
||||
return ans
|
||||
}
|
||||
|
||||
func prefix_for_spec(spec string) string {
|
||||
sb := strings.Builder{}
|
||||
for _, ec := range cached_parse_spec(spec) {
|
||||
sb.WriteString(ec.prefix())
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func suffix_for_spec(spec string) string {
|
||||
sb := strings.Builder{}
|
||||
for _, ec := range cached_parse_spec(spec) {
|
||||
sb.WriteString(ec.suffix())
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package style
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestANSIStyleContext(t *testing.T) {
|
||||
var ctx = Context{AllowEscapeCodes: false}
|
||||
sprint := ctx.SprintFunc("bold")
|
||||
if sprint("test") != "test" {
|
||||
t.Fatal("AllowEscapeCodes=false not respected")
|
||||
}
|
||||
ctx.AllowEscapeCodes = true
|
||||
if sprint("test") == "test" {
|
||||
t.Fatal("AllowEscapeCodes=true not respected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestANSIStyleSprint(t *testing.T) {
|
||||
var ctx = Context{AllowEscapeCodes: true}
|
||||
|
||||
test := func(spec string, prefix string, suffix string) {
|
||||
actual := ctx.SprintFunc(spec)(" ")
|
||||
expected := prefix + " " + suffix
|
||||
if actual != expected {
|
||||
t.Fatalf("Formatting with spec: %s failed expected != actual: %#v != %#v", spec, expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
test("", "", "")
|
||||
test("bold", "\x1b[1m", "\x1b[221m")
|
||||
test("bold fg=red u=curly", "\x1b[1;4:3;31m", "\x1b[221;4:0;39m")
|
||||
test("fg=123", "\x1b[38:5:123m", "\x1b[39m")
|
||||
test("fg=15", "\x1b[97m", "\x1b[39m")
|
||||
test("bg=15", "\x1b[107m", "\x1b[49m")
|
||||
test("fg=#123", "\x1b[38:2:17:34:51m", "\x1b[39m")
|
||||
test("fg=rgb:1/2/3", "\x1b[38:2:17:34:51m", "\x1b[39m")
|
||||
test("bg=123", "\x1b[48:5:123m", "\x1b[49m")
|
||||
test("uc=123", "\x1b[58:5:123m", "\x1b[59m")
|
||||
test("uc=1", "\x1b[58:5:1m", "\x1b[59m")
|
||||
|
||||
actual := ctx.UrlFunc("u=curly uc=cyan")("http://moo.com", "___")
|
||||
expected := "\x1b[4:3;58:5:6m\x1b]8;;http://moo.com\x1b\\___\x1b]8;;\x1b\\\x1b[4:0;59m"
|
||||
if actual != expected {
|
||||
t.Fatalf("Formatting URL failed expected != actual: %#v != %#v", expected, actual)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user