Skip to content
Myr

Add support for ANSI color codes

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Junegunn Choi · committed by Junegunn Choi · parent d80a41b · Browse files · 11 files+451 added−24 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+451 added−24 removed

  • other:+451 added−24 removed

11 files+451 added−24 removed

added:src/curses/curses_test.go+14 added
1package curses23import (4 "testing"5)67func TestPairFor(t *testing.T) {8 if PairFor(30, 50) != PairFor(30, 50) {9 t.Fail()10 }11 if PairFor(-1, 10) != PairFor(-1, 10) {12 t.Fail()13 }14}
modified:src/curses/curses.go+26 added-8 removed
76 unmodified lines
77 ColSpinner78 ColInfo79 ColCursor80 ColSelected81 ColUser82)8384const (85 doubleClickDuration = 500 * time.Millisecond
17 unmodified lines
103var (104 _buf []byte105 _in *os.File106 _color func(int, bool) C.int107 _colorMap map[int]int108 _prevDownTime time.Time109 _prevDownY int110 _clickY []int111 DarkBG C.short112)113114func init() {115 _prevDownTime = time.Unix(0, 0)116 _clickY = []int{}117 _colorMap = make(map[int]int)118}119120func attrColored(pair int, bold bool) C.int {121 var attr C.int
81 unmodified lines
203 C.use_default_colors()204 bg = -1205 }206 if color256 {207 DarkBG = 236208 C.init_pair(ColPrompt, 110, bg)209 C.init_pair(ColMatch, 108, bg)205 C.init_pair(ColCurrent, 254, 236)206 C.init_pair(ColCurrentMatch, 151, 236)210 C.init_pair(ColCurrent, 254, DarkBG)211 C.init_pair(ColCurrentMatch, 151, DarkBG)212 C.init_pair(ColSpinner, 148, bg)213 C.init_pair(ColInfo, 144, bg)209 C.init_pair(ColCursor, 161, 236)210 C.init_pair(ColSelected, 168, 236)214 C.init_pair(ColCursor, 161, DarkBG)215 C.init_pair(ColSelected, 168, DarkBG)216 } else {217 DarkBG = C.COLOR_BLACK218 C.init_pair(ColPrompt, C.COLOR_BLUE, bg)219 C.init_pair(ColMatch, C.COLOR_GREEN, bg)214 C.init_pair(ColCurrent, C.COLOR_YELLOW, C.COLOR_BLACK)215 C.init_pair(ColCurrentMatch, C.COLOR_GREEN, C.COLOR_BLACK)220 C.init_pair(ColCurrent, C.COLOR_YELLOW, DarkBG)221 C.init_pair(ColCurrentMatch, C.COLOR_GREEN, DarkBG)222 C.init_pair(ColSpinner, C.COLOR_GREEN, bg)223 C.init_pair(ColInfo, C.COLOR_WHITE, bg)218 C.init_pair(ColCursor, C.COLOR_RED, C.COLOR_BLACK)219 C.init_pair(ColSelected, C.COLOR_MAGENTA, C.COLOR_BLACK)224 C.init_pair(ColCursor, C.COLOR_RED, DarkBG)225 C.init_pair(ColSelected, C.COLOR_MAGENTA, DarkBG)226 }227 _color = attrColored228 } else {229 _color = attrMono
203 unmodified lines
433434func Refresh() {435 C.refresh()436}437438func PairFor(fg int, bg int) int {439 key := (fg << 8) + bg440 if found, prs := _colorMap[key]; prs {441 return found442 }443444 id := len(_colorMap) + ColUser445 C.init_pair(C.short(id), C.short(fg), C.short(bg))446 _colorMap[key] = id447 return id448}
modified:src/util/util.go+11 added
25 unmodified lines
26 }27 return second28}2930// Constrain32 limits the given 32-bit integer with the upper and lower bounds31func Constrain32(val int32, min int32, max int32) int32 {32 if val < min {33 return min34 }35 if val > max {36 return max37 }38 return val39}4041// Constrain limits the given integer with the upper and lower bounds42func Constrain(val int, min int, max int) int {43 if val < min {44 return min
23 unmodified lines
added:src/ansi_test.go+91 added
1package fzf23import (4 "fmt"5 "testing"6)78func TestExtractColor(t *testing.T) {9 assert := func(offset AnsiOffset, b int32, e int32, fg int, bg int, bold bool) {10 if offset.offset[0] != b || offset.offset[1] != e ||11 offset.color.fg != fg || offset.color.bg != bg || offset.color.bold != bold {12 t.Error(offset, b, e, fg, bg, bold)13 }14 }1516 src := "hello world"17 clean := "\x1b[0m"18 check := func(assertion func(ansiOffsets []AnsiOffset)) {19 output, ansiOffsets := ExtractColor(&src)20 if *output != "hello world" {21 t.Errorf("Invalid output: {}", output)22 }23 fmt.Println(src, ansiOffsets, clean)24 assertion(ansiOffsets)25 }2627 check(func(offsets []AnsiOffset) {28 if len(offsets) > 0 {29 t.Fail()30 }31 })3233 src = "\x1b[0mhello world"34 check(func(offsets []AnsiOffset) {35 if len(offsets) > 0 {36 t.Fail()37 }38 })3940 src = "\x1b[1mhello world"41 check(func(offsets []AnsiOffset) {42 if len(offsets) != 1 {43 t.Fail()44 }45 assert(offsets[0], 0, 11, -1, -1, true)46 })4748 src = "hello \x1b[34;45;1mworld"49 check(func(offsets []AnsiOffset) {50 if len(offsets) != 1 {51 t.Fail()52 }53 assert(offsets[0], 6, 11, 4, 5, true)54 })5556 src = "hello \x1b[34;45;1mwor\x1b[34;45;1mld"57 check(func(offsets []AnsiOffset) {58 if len(offsets) != 1 {59 t.Fail()60 }61 assert(offsets[0], 6, 11, 4, 5, true)62 })6364 src = "hello \x1b[34;45;1mwor\x1b[0mld"65 check(func(offsets []AnsiOffset) {66 if len(offsets) != 1 {67 t.Fail()68 }69 assert(offsets[0], 6, 9, 4, 5, true)70 })7172 src = "hello \x1b[34;48;5;233;1mwo\x1b[38;5;161mr\x1b[0ml\x1b[38;5;161md"73 check(func(offsets []AnsiOffset) {74 if len(offsets) != 3 {75 t.Fail()76 }77 assert(offsets[0], 6, 8, 4, 233, true)78 assert(offsets[1], 8, 9, 161, 233, true)79 assert(offsets[2], 10, 11, 161, -1, false)80 })8182 // {38,48};5;{38,48}83 src = "hello \x1b[38;5;38;48;5;48;1mwor\x1b[38;5;48;48;5;38ml\x1b[0md"84 check(func(offsets []AnsiOffset) {85 if len(offsets) != 2 {86 t.Fail()87 }88 assert(offsets[0], 6, 9, 38, 48, true)89 assert(offsets[1], 9, 10, 48, 38, true)90 })91}
added:src/ansi.go+141 added
1package fzf23import (4 "bytes"5 "regexp"6 "strconv"7 "strings"8)910type AnsiOffset struct {11 offset [2]int3212 color ansiState13}1415type ansiState struct {16 fg int17 bg int18 bold bool19}2021func (s *ansiState) colored() bool {22 return s.fg != -1 || s.bg != -1 || s.bold23}2425func (s *ansiState) equals(t *ansiState) bool {26 if t == nil {27 return !s.colored()28 }29 return s.fg == t.fg && s.bg == t.bg && s.bold == t.bold30}3132var ansiRegex *regexp.Regexp3334func init() {35 ansiRegex = regexp.MustCompile("\x1b\\[[0-9;]*m")36}3738func ExtractColor(str *string) (*string, []AnsiOffset) {39 offsets := make([]AnsiOffset, 0)4041 var output bytes.Buffer42 var state *ansiState4344 idx := 045 for _, offset := range ansiRegex.FindAllStringIndex(*str, -1) {46 output.WriteString((*str)[idx:offset[0]])47 newLen := int32(output.Len())48 newState := interpretCode((*str)[offset[0]:offset[1]], state)4950 if !newState.equals(state) {51 if state != nil {52 // Update last offset53 (&offsets[len(offsets)-1]).offset[1] = int32(output.Len())54 }5556 if newState.colored() {57 // Append new offset58 state = newState59 offsets = append(offsets, AnsiOffset{[2]int32{newLen, newLen}, *state})60 } else {61 // Discard state62 state = nil63 }64 }6566 idx = offset[1]67 }6869 rest := (*str)[idx:]70 if len(rest) > 0 {71 output.WriteString(rest)72 if state != nil {73 // Update last offset74 (&offsets[len(offsets)-1]).offset[1] = int32(output.Len())75 }76 }77 outputStr := output.String()78 return &outputStr, offsets79}8081func interpretCode(ansiCode string, prevState *ansiState) *ansiState {82 // State83 var state *ansiState84 if prevState == nil {85 state = &ansiState{-1, -1, false}86 } else {87 state = &ansiState{prevState.fg, prevState.bg, prevState.bold}88 }8990 ptr := &state.fg91 state256 := 09293 init := func() {94 state.fg = -195 state.bg = -196 state.bold = false97 state256 = 098 }99100 ansiCode = ansiCode[2 : len(ansiCode)-1]101 for _, code := range strings.Split(ansiCode, ";") {102 if num, err := strconv.Atoi(code); err == nil {103 switch state256 {104 case 0:105 switch num {106 case 38:107 ptr = &state.fg108 state256++109 case 48:110 ptr = &state.bg111 state256++112 case 39:113 state.fg = -1114 case 49:115 state.bg = -1116 case 1:117 state.bold = true118 case 0:119 init()120 default:121 if num >= 30 && num <= 37 {122 state.fg = num - 30123 } else if num >= 40 && num <= 47 {124 state.bg = num - 40125 }126 }127 case 1:128 switch num {129 case 5:130 state256++131 default:132 state256 = 0133 }134 case 2:135 *ptr = num136 state256 = 0137 }138 }139 }140 return state141}
modified:src/core.go+30 added-3 removed
61 unmodified lines
6263 // Event channel64 eventBox := util.NewEventBox()6566 // ANSI code processor67 extractColors := func(data *string) (*string, []AnsiOffset) {68 // By default, we do nothing69 return data, nil70 }71 if opts.Ansi {72 if opts.Color {73 extractColors = func(data *string) (*string, []AnsiOffset) {74 return ExtractColor(data)75 }76 } else {77 // When color is disabled but ansi option is given,78 // we simply strip out ANSI codes from the input79 extractColors = func(data *string) (*string, []AnsiOffset) {80 trimmed, _ := ExtractColor(data)81 return trimmed, nil82 }83 }84 }8586 // Chunk list87 var chunkList *ChunkList88 if len(opts.WithNth) == 0 {89 chunkList = NewChunkList(func(data *string, index int) *Item {90 data, colors := extractColors(data)91 return &Item{71 text: data,72 index: uint32(index),73 rank: Rank{0, 0, uint32(index)}}92 text: data,93 index: uint32(index),94 colors: colors,95 rank: Rank{0, 0, uint32(index)}}96 })97 } else {98 chunkList = NewChunkList(func(data *string, index int) *Item {99 tokens := Tokenize(data, opts.Delimiter)100 item := Item{101 text: Transform(tokens, opts.WithNth).whole,102 origText: data,103 index: uint32(index),104 colors: nil,105 rank: Rank{0, 0, uint32(index)}}106107 trimmed, colors := extractColors(item.text)108 item.text = trimmed109 item.colors = colors110 return &item111 })112 }113
127 unmodified lines
modified:src/item_test.go+30 added
1 unmodified line
23import (4 "sort"5 "testing"67 "github.com/junegunn/fzf/src/curses"8)910func TestOffsetSort(t *testing.T) {11 offsets := []Offset{
61 unmodified lines
73 items[4] != &item5 || items[5] != &item3 {74 t.Error(items)75 }76}7778func TestColorOffset(t *testing.T) {79 // ------------ 20 ---- -- ----80 // ++++++++ ++++++++++81 // --++++++++-- --++++++++++---82 item := Item{83 offsets: []Offset{Offset{5, 15}, Offset{25, 35}},84 colors: []AnsiOffset{85 AnsiOffset{[2]int32{0, 20}, ansiState{1, 5, false}},86 AnsiOffset{[2]int32{22, 27}, ansiState{2, 6, true}},87 AnsiOffset{[2]int32{30, 32}, ansiState{3, 7, false}},88 AnsiOffset{[2]int32{33, 40}, ansiState{4, 8, true}}}}89 // [{[0 5] 9 false} {[5 15] 99 false} {[15 20] 9 false} {[22 25] 10 true} {[25 35] 99 false} {[35 40] 11 true}]9091 offsets := item.ColorOffsets(99, false, true)92 assert := func(idx int, b int32, e int32, c int, bold bool) {93 o := offsets[idx]94 if o.offset[0] != b || o.offset[1] != e || o.color != c || o.bold != bold {95 t.Error(o)96 }97 }98 assert(0, 0, 5, curses.ColUser, false)99 assert(1, 5, 15, 99, false)100 assert(2, 15, 20, curses.ColUser, false)101 assert(3, 22, 25, curses.ColUser+1, true)102 assert(4, 25, 35, 99, false)103 assert(5, 35, 40, curses.ColUser+2, true)104}
modified:src/item.go+84 added
1package fzf23import (4 "github.com/junegunn/fzf/src/curses"5)67// Offset holds two 32-bit integers denoting the offsets of a matched substring8type Offset [2]int32910type ColorOffset struct {11 offset [2]int3212 color int13 bold bool14}1516// Item represents each input line17type Item struct {18 text *string19 origText *string20 transformed *Transformed21 index uint3222 offsets []Offset23 colors []AnsiOffset24 rank Rank25}2627// Rank is used to sort the search result
37 unmodified lines
65 }66 return *i.text67}6869func (item *Item) ColorOffsets(color int, bold bool, current bool) []ColorOffset {70 if len(item.colors) == 0 {71 offsets := make([]ColorOffset, 0)72 for _, off := range item.offsets {73 offsets = append(offsets, ColorOffset{offset: off, color: color, bold: bold})74 }75 return offsets76 }7778 // Find max column79 var maxCol int32 = 080 for _, off := range item.offsets {81 if off[1] > maxCol {82 maxCol = off[1]83 }84 }85 for _, ansi := range item.colors {86 if ansi.offset[1] > maxCol {87 maxCol = ansi.offset[1]88 }89 }90 cols := make([]int, maxCol)9192 for colorIndex, ansi := range item.colors {93 for i := ansi.offset[0]; i < ansi.offset[1]; i++ {94 cols[i] = colorIndex + 1 // XXX95 }96 }9798 for _, off := range item.offsets {99 for i := off[0]; i < off[1]; i++ {100 cols[i] = -1101 }102 }103104 // sort.Sort(ByOrder(offsets))105106 // Merge offsets107 // ------------ ---- -- ----108 // ++++++++ ++++++++++109 // --++++++++-- --++++++++++---110 curr := 0111 start := 0112 offsets := make([]ColorOffset, 0)113 add := func(idx int) {114 if curr != 0 && idx > start {115 if curr == -1 {116 offsets = append(offsets, ColorOffset{117 offset: Offset{int32(start), int32(idx)}, color: color, bold: bold})118 } else {119 ansi := item.colors[curr-1]120 bg := ansi.color.bg121 if current {122 bg = int(curses.DarkBG)123 }124 offsets = append(offsets, ColorOffset{125 offset: Offset{int32(start), int32(idx)},126 color: curses.PairFor(ansi.color.fg, bg),127 bold: ansi.color.bold || bold})128 }129 }130 }131 for idx, col := range cols {132 if col != curr {133 add(idx)134 start = idx135 curr = col136 }137 }138 add(int(maxCol))139 return offsets140}141142// ByOrder is for sorting substring offsets143type ByOrder []Offset144145func (a ByOrder) Len() int {
64 unmodified lines
modified:src/options.go+7 added
27 unmodified lines
28 (e.g. 'history | fzf --tac --no-sort')2930 Interface31 -m, --multi Enable multi-select with tab/shift-tab32 --ansi Interpret ANSI color codes and remove from output33 --no-mouse Disable mouse34 +c, --no-color Disable colors35 +2, --no-256 Disable 256-color36 --black Use black background
44 unmodified lines
81 Delimiter *regexp.Regexp82 Sort int83 Tac bool84 Multi bool85 Ansi bool86 Mouse bool87 Color bool88 Color256 bool89 Black bool
17 unmodified lines
107 Delimiter: nil,108 Sort: 1000,109 Tac: false,110 Multi: false,111 Ansi: false,112 Mouse: true,113 Color: true,114 Color256: strings.Contains(os.Getenv("TERM"), "256"),115 Black: false,
113 unmodified lines
229 case "-m", "--multi":230 opts.Multi = true231 case "+m", "--no-multi":232 opts.Multi = false233 case "--ansi":234 opts.Ansi = true235 case "--no-ansi":236 opts.Ansi = false237 case "--no-mouse":238 opts.Mouse = false239 case "+c", "--no-color":240 opts.Color = false
77 unmodified lines
modified:src/pattern.go+1 added
262 unmodified lines
263 origText: item.origText,264 transformed: item.transformed,265 index: item.index,266 offsets: offsets,267 colors: item.colors,268 rank: Rank{0, 0, item.index}}269}270271func (p *Pattern) fuzzyMatch(item *Item) (int, int) {
50 unmodified lines
modified:src/terminal.go+16 added-13 removed
249 unmodified lines
250 C.CPrint(C.ColCurrent, true, ">")251 } else {252 C.CPrint(C.ColCurrent, true, " ")253 }254 t.printHighlighted(item, true, C.ColCurrent, C.ColCurrentMatch)254 t.printHighlighted(item, true, C.ColCurrent, C.ColCurrentMatch, true)255 } else {256 C.CPrint(C.ColCursor, true, " ")257 if selected {258 C.CPrint(C.ColSelected, true, ">")259 } else {260 C.Print(" ")261 }262 t.printHighlighted(item, false, 0, C.ColMatch)262 t.printHighlighted(item, false, 0, C.ColMatch, false)263 }264}265266func trimRight(runes []rune, width int) ([]rune, int) {
31 unmodified lines
298 }299 return runes, trimmed300}301302func (*Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int) {302func (*Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int, current bool) {303 var maxe int32304 for _, offset := range item.offsets {305 if offset[1] > maxe {306 maxe = offset[1]
1 unmodified line
308 }309310 // Overflow311 text := []rune(*item.text)312 offsets := item.offsets312 offsets := item.ColorOffsets(col2, bold, current)313 maxWidth := C.MaxX() - 3314 fullWidth := displayWidth(text)315 if fullWidth > maxWidth {316 // Stri..
10 unmodified lines
327 var diff int32328 text, diff = trimLeft(text, maxWidth-2)329330 // Transform offsets331 offsets = make([]Offset, len(item.offsets))332 for idx, offset := range item.offsets {333 b, e := offset[0], offset[1]331 for idx, offset := range offsets {332 b, e := offset.offset[0], offset.offset[1]333 b += 2 - diff334 e += 2 - diff335 b = util.Max32(b, 2)336 if b < e {338 offsets[idx] = Offset{b, e}337 offsets[idx].offset[0] = b338 offsets[idx].offset[1] = e339 }340 }341 text = append([]rune(".."), text...)342 }343 }344345 sort.Sort(ByOrder(offsets))345 var index int32346 var substr string347 var prefixWidth int348 maxOffset := int32(len(text))349 for _, offset := range offsets {350 b := util.Max32(index, offset[0])351 e := util.Max32(index, offset[1])350 b := util.Constrain32(offset.offset[0], index, maxOffset)351 e := util.Constrain32(offset.offset[1], index, maxOffset)352353 substr, prefixWidth = processTabs(text[index:b], prefixWidth)354 C.CPrint(col1, bold, substr)355356 substr, prefixWidth = processTabs(text[b:e], prefixWidth)357 C.CPrint(col2, bold, substr)357 C.CPrint(offset.color, bold, substr)358359 index = e360 if index >= maxOffset {361 break362 }363 }361 if index < int32(len(text)) {364 if index < maxOffset {365 substr, _ = processTabs(text[index:], prefixWidth)366 C.CPrint(col1, bold, substr)367 }368}
344 unmodified lines