Switch ANSI rendering to termenv to automatically convert colors between color-profiles

This commit is contained in:
Christian Muehlhaeuser
2020-01-13 04:40:43 +01:00
parent 5d74978da0
commit 743ecf40c5
13 changed files with 53 additions and 172 deletions
+8 -74
View File
@@ -2,15 +2,10 @@ package ansi
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"strconv"
"text/template"
"github.com/logrusorgru/aurora"
"github.com/lucasb-eyer/go-colorful"
"github.com/muesli/termenv"
)
// BaseElement renders a styled primitive element.
@@ -21,50 +16,6 @@ type BaseElement struct {
Style StylePrimitive
}
func color(c *string) (uint8, error) {
if c == nil || len(*c) == 0 {
return 0, errors.New("invalid color")
}
if (*c)[0] == '#' {
i, err := hexToANSIColor(*c)
return uint8(i), err
}
i, err := strconv.Atoi(*c)
return uint8(i), err
}
func colorSeq(fg *string, bg *string) (string, error) {
fc := ""
bc := ""
if fg != nil {
fc = *fg
}
if bg != nil {
bc = *bg
}
fs := ""
bs := ""
f, err := colorful.Hex(fc)
if err == nil {
fs = fmt.Sprintf("38;2;%d;%d;%d", uint8(f.R*255), uint8(f.G*255), uint8(f.B*255))
}
b, err := colorful.Hex(bc)
if err == nil {
bs = fmt.Sprintf("48;2;%d;%d;%d", uint8(b.R*255), uint8(b.G*255), uint8(b.B*255))
}
if len(fs) > 0 || len(bs) > 0 {
seq := "\x1b[" + fs
if len(fs) > 0 {
seq += ";"
}
return seq + bs + "m", nil
}
return "", errors.New("invalid color")
}
func formatToken(format string, token string) (string, error) {
var b bytes.Buffer
@@ -85,33 +36,16 @@ func renderText(w io.Writer, rules StylePrimitive, s string) {
return
}
truecolor := os.Getenv("COLORTERM") == "truecolor"
// FIXME: ugly true-color ANSI support hack
if truecolor {
seq, err := colorSeq(rules.Color, rules.BackgroundColor)
if err == nil {
s = seq + s
} else {
truecolor = false
}
}
p := termenv.SupportedColorProfile()
out := termenv.String(s)
out := aurora.Reset(s)
if !truecolor {
if rules.Color != nil {
i, err := color(rules.Color)
if err == nil {
out = out.Index(i)
}
out = out.Foreground(p.Color(*rules.Color))
}
if rules.BackgroundColor != nil {
i, err := color(rules.BackgroundColor)
if err == nil {
out = out.BgIndex(i)
}
}
out = out.Background(p.Color(*rules.BackgroundColor))
}
if rules.Underline != nil && *rules.Underline {
out = out.Underline()
}
@@ -122,10 +56,10 @@ func renderText(w io.Writer, rules StylePrimitive, s string) {
out = out.Italic()
}
if rules.CrossedOut != nil && *rules.CrossedOut {
out = out.CrossedOut()
out = out.CrossOut()
}
if rules.Overlined != nil && *rules.Overlined {
out = out.Overlined()
out = out.Overline()
}
if rules.Inverse != nil && *rules.Inverse {
out = out.Reverse()
-54
View File
@@ -1,9 +1,5 @@
package ansi
import (
"github.com/lucasb-eyer/go-colorful"
)
// Chroma holds all the chroma settings.
type Chroma struct {
Text StylePrimitive `json:"text,omitempty"`
@@ -229,53 +225,3 @@ func cascadeStyle(parent StyleBlock, child StyleBlock, toBlock bool) StyleBlock
return s
}
func hexToANSIColor(h string) (int, error) {
c, err := colorful.Hex(h)
if err != nil {
return 0, err
}
v2ci := func(v float64) int {
if v < 48 {
return 0
}
if v < 115 {
return 1
}
return int((v - 35) / 40)
}
// Calculate the nearest 0-based color index at 16..231
r := v2ci(c.R * 255.0) // 0..5 each
g := v2ci(c.G * 255.0)
b := v2ci(c.B * 255.0)
ci := 36*r + 6*g + b /* 0..215 */
// Calculate the represented colors back from the index
i2cv := [6]int{0, 0x5f, 0x87, 0xaf, 0xd7, 0xff}
cr := i2cv[r] // r/g/b, 0..255 each
cg := i2cv[g]
cb := i2cv[b]
// Calculate the nearest 0-based gray index at 232..255
var grayIdx int
average := (r + g + b) / 3
if average > 238 {
grayIdx = 23
} else {
grayIdx = (average - 3) / 10 // 0..23
}
gv := 8 + 10*grayIdx // same value for r/g/b, 0..255
// Return the one which is nearer to the original input rgb value
c2 := colorful.Color{R: float64(cr) / 255.0, G: float64(cg) / 255.0, B: float64(cb) / 255.0}
g2 := colorful.Color{R: float64(gv) / 255.0, G: float64(gv) / 255.0, B: float64(gv) / 255.0}
colorDist := c.DistanceLab(c2)
grayDist := c.DistanceLab(g2)
if colorDist <= grayDist {
return 16 + ci, nil
}
return 232 + grayIdx, nil
}
+1 -2
View File
@@ -4,10 +4,9 @@ go 1.13
require (
github.com/alecthomas/chroma v0.7.0
github.com/logrusorgru/aurora v0.0.0-20191116043053-66b7ad493a23
github.com/lucasb-eyer/go-colorful v1.0.3
github.com/microcosm-cc/bluemonday v1.0.2
github.com/muesli/reflow v0.0.0-20191216070243-e5efeac4e302
github.com/muesli/termenv v0.0.0-20200113033546-8f8d5d08dedf
github.com/olekukonko/tablewriter v0.0.4
github.com/yuin/goldmark v1.1.19
)
+4 -2
View File
@@ -20,14 +20,14 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.1.6 h1:CqB4MjHw0MFCDj+PHHjiESmHX+N7t0tJzKvC6M97BRg=
github.com/dlclark/regexp2 v1.1.6/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=
github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f h1:5CjVwnuUcp5adK4gmY6i72gpVFVnZDP2h5TmPScB6u4=
github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=
github.com/gorilla/csrf v1.6.0/go.mod h1:7tSf8kmjNYr7IWDCYhd3U8Ck34iQ/Yw5CJu7bAkHEGI=
github.com/gorilla/handlers v1.4.1/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/logrusorgru/aurora v0.0.0-20191116043053-66b7ad493a23 h1:Wp7NjqGKGN9te9N/rvXYRhlVcrulGdxnz8zadXWs7fc=
github.com/logrusorgru/aurora v0.0.0-20191116043053-66b7ad493a23/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4=
github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac=
github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
@@ -40,6 +40,8 @@ github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/le
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/muesli/reflow v0.0.0-20191216070243-e5efeac4e302 h1:jOh3Kh03uOFkRPV3PI4Am5tqACv2aELgbPgr7YgNX00=
github.com/muesli/reflow v0.0.0-20191216070243-e5efeac4e302/go.mod h1:I9bWAt7QTg/que/qmUCJBGlj7wEq8OAFBjPNjc6xK4I=
github.com/muesli/termenv v0.0.0-20200113033546-8f8d5d08dedf h1:l4WaujeZsr44fY6kYHlDlS1RlbW9Xz+edwW8LUqCYMw=
github.com/muesli/termenv v0.0.0-20200113033546-8f8d5d08dedf/go.mod h1:QAW21ZWi5eDIAoYsevV52sibdVVCl44P+TvI0C0VKEU=
github.com/nkovacs/streamquote v0.0.0-20170412213628-49af9bddb229/go.mod h1:0aYXnNPJ8l7uZxf45rWW1a/uME32OF0rhiYGNQ2oF2E=
github.com/olekukonko/tablewriter v0.0.4 h1:vHD/YYe1Wolo78koG299f7V/VAS08c6IpCLn+Ejf/w8=
github.com/olekukonko/tablewriter v0.0.4/go.mod h1:zq6QwlOf5SlnkVbMSr5EoBv3636FWnp+qbPhuoO21uA=
+2 -2
View File
@@ -1,3 +1,3 @@
1. First Item                                                                   
2. Second Item                                                                  
1. First Item                                                                   
2. Second Item                                                                  
+3 -3
View File
@@ -1,3 +1,3 @@
 => h1 <= 
 ## h2 
 ### h3
 => h1 <= 
 ## h2 
 ### h3
+1 -1
View File
@@ -1 +1 @@
Image [Image: https://charm.sh/logo.png]. 
Image [Image: https://charm.sh/logo.png]. 
+4 -4
View File
@@ -1,6 +1,6 @@
 If you want to make a more significant change, please first open an issue     
 https://github.com/twpayne/chezmoi/issues/new to discuss the change that you  
 want to make. Dave Cheney gives a good rationale                              
 https://dave.cheney.net/2019/02/18/talk-then-code as to why this is important.
 If you want to make a more significant change, please first open an issue     
 https://github.com/twpayne/chezmoi/issues/new to discuss the change that you  
 want to make. Dave Cheney gives a good rationale                              
 https://dave.cheney.net/2019/02/18/talk-then-code as to why this is important.
+7 -7
View File
@@ -1,10 +1,10 @@
                                                                              
 • Getting started                                                             
 • Developing locally                                                          
 • Documentation changes                                                       
 • Contributing changes                                                        
 • Managing releases                                                           
 • Packaging                                                                   
 • Updating the website                                                        
 • Getting started                                                             
 • Developing locally                                                          
 • Documentation changes                                                       
 • Contributing changes                                                        
 • Managing releases                                                           
 • Packaging                                                                   
 • Updating the website                                                        
+1 -1
View File
@@ -1 +1 @@
This is a link (https://charm.sh). 
This is a link (https://charm.sh). 
+3 -3
View File
@@ -1,4 +1,4 @@
• First Item                                                                    
    • Nested List Item                                                          
• Second Item                                                                   
• First Item                                                                    
    • Nested List Item                                                          
• Second Item                                                                   
+14 -14
View File
@@ -1,36 +1,36 @@
  Gold                                                                         
  Gold                                                                         
                                                                               
 Render markdown on the CLI, with pizzazz!                                     
 Render markdown on the CLI, with pizzazz!                                     
                                                                               
 ## What is it?                                                                
 ## What is it?                                                                
                                                                               
 Gold is a Golang library that allows you to use JSON based stylesheets to     
 render Markdown files in the terminal. Just like CSS, you can define color and
 style attributes on Markdown elements. The difference is that you use ANSI    
 color and terminal codes instead of CSS properties and hex colors.            
                                                                               
 ## Usage                                                                      
 ## Usage                                                                      
                                                                               
 See cmd/gold /cmd/gold/.                                                      
 See cmd/gold /cmd/gold/.                                                      
                                                                               
 ## Example Output                                                             
 ## Example Output                                                             
                                                                               
 Image: Gold Dark Style →                                                      
 https://github.com/charmbracelet/gold/raw/master/styles/gallery/dark.png      
 https://github.com/charmbracelet/gold/raw/master/styles/gallery/dark.png      
                                                                               
 Check out the Gold Style Gallery                                              
 https://github.com/charmbracelet/gold/blob/master/styles/gallery/README.md!   
 Check out the Gold Style Gallery                                              
 https://github.com/charmbracelet/gold/blob/master/styles/gallery/README.md!   
                                                                               
 ## Colors                                                                     
 ## Colors                                                                     
                                                                               
 Currently  gold  uses the Aurora ANSI colors                                  
 https://godoc.org/github.com/logrusorgru/aurora#Index.                        
 Currently  gold  uses the Aurora ANSI colors                                  
 https://godoc.org/github.com/logrusorgru/aurora#Index.                        
                                                                               
 ## Development                                                                
 ## Development                                                                
                                                                               
 Style definitions located in  styles/  can be embedded into the binary by     
 running statik https://github.com/rakyll/statik:                              
 running statik https://github.com/rakyll/statik:                              
                                                                               
   statik -f -src styles -include "*.json"                                     
                                                                               
+2 -2
View File
@@ -1,3 +1,3 @@
✓ Finished Task                                                                 
✗ Outstanding Task                                                              
✓ Finished Task                                                                 
✗ Outstanding Task