Skip to content

Commit

Permalink
added ANSI color parsing and displaying colors in preview (closes #29) (
Browse files Browse the repository at this point in the history
#154)

* added ANSI color parsing and displaying colors in preview

* changed color parser to use less regex

* removed unused error return from color parser
  • Loading branch information
cynicade authored Jul 3, 2022
1 parent 76fb6bd commit 3788372
Showing 1 changed file with 56 additions and 4 deletions.
60 changes: 56 additions & 4 deletions fuzzyfinder.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"flag"
"fmt"
"reflect"
"regexp"
"sort"
"strings"
"sync"
Expand All @@ -23,8 +24,9 @@ import (

var (
// ErrAbort is returned from Find* functions if there are no selections.
ErrAbort = errors.New("abort")
errEntered = errors.New("entered")
ErrAbort = errors.New("abort")
errEntered = errors.New("entered")
colorsRegex = regexp.MustCompile(`\[[0-9;]*m`)
)

// Finds the minimum value among the arguments
Expand Down Expand Up @@ -276,6 +278,53 @@ func (f *finder) _draw() {
}
}

func parseColor(rs *[]rune) (tcell.Color, bool) {
// only parses for 16 colors
// convert to string for easier parsing
str := string(*rs)
ansi := colorsRegex.FindStringSubmatch(str)
var bold bool

if len(ansi) == 0 {
// no color is being passed, return defaults
return tcell.ColorDefault, false
}

// ANSI color value is being passed
// find if bold is specified
if len(ansi[0]) > 4 && ansi[0][3:5] == ";1" {
bold = true
}

// find the color value
color := ansi[0][1:3]

// strip color codes (also strips trailing '[0m')
stripped := colorsRegex.ReplaceAllString(str, "")
*rs = []rune(stripped)

switch color {
case "30":
return tcell.ColorBlack, bold
case "31":
return tcell.ColorRed, bold
case "32":
return tcell.ColorGreen, bold
case "33":
return tcell.ColorYellow, bold
case "34":
return tcell.ColorBlue, bold
case "35":
return tcell.ColorDarkMagenta, bold
case "36":
return tcell.ColorDarkCyan, bold
case "37":
return tcell.ColorWhite, bold
default:
return tcell.ColorDefault, bold
}
}

func (f *finder) _drawPreview() {
if f.opt.previewFunc == nil {
return
Expand Down Expand Up @@ -367,6 +416,8 @@ func (f *finder) _drawPreview() {
}
j := i - width/2 - 2 // Two spaces.
l := prevLines[h-1]
// parse colors here and strip color codes from runes
col, isBold := parseColor(&l)
if j >= len(l) {
w++
continue
Expand All @@ -385,8 +436,9 @@ func (f *finder) _drawPreview() {
}

style := tcell.StyleDefault.
Foreground(tcell.ColorDefault).
Background(tcell.ColorDefault)
Foreground(col).
Background(tcell.ColorDefault).
Bold(isBold)
f.term.SetContent(w, h, l[j], nil, style)
w += rw
}
Expand Down

0 comments on commit 3788372

Please sign in to comment.