Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added ANSI color parsing and displaying colors in preview (closes #29) #154

Merged
merged 3 commits into from
Jul 3, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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`)
)

type state struct {
Expand Down Expand Up @@ -263,6 +265,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 @@ -354,6 +403,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 @@ -372,8 +423,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