summaryrefslogtreecommitdiff
path: root/src/ansi.go
diff options
context:
space:
mode:
authorJunegunn Choi <junegunn.c@gmail.com>2019-03-06 19:05:05 +0900
committerJunegunn Choi <junegunn.c@gmail.com>2019-03-06 19:05:05 +0900
commitef577a65094a38f82b2c18dfd3e524eb50748503 (patch)
tree54b4cb94db71b31e781ab2405732f812e6dd0df2 /src/ansi.go
parentb7c6838e4574fc07699fd7ea52e893021853cb42 (diff)
downloadfzf-ef577a65094a38f82b2c18dfd3e524eb50748503.tar.gz
Preserve the original color of each token when using --with-nth with --ansi
Close #1500
Diffstat (limited to 'src/ansi.go')
-rw-r--r--src/ansi.go50
1 files changed, 50 insertions, 0 deletions
diff --git a/src/ansi.go b/src/ansi.go
index d7c81d30..cc458d15 100644
--- a/src/ansi.go
+++ b/src/ansi.go
@@ -2,6 +2,7 @@ package fzf
import (
"bytes"
+ "fmt"
"regexp"
"strconv"
"strings"
@@ -32,6 +33,55 @@ func (s *ansiState) equals(t *ansiState) bool {
return s.fg == t.fg && s.bg == t.bg && s.attr == t.attr
}
+func (s *ansiState) ToString() string {
+ if !s.colored() {
+ return "\x1b[m"
+ }
+
+ ret := ""
+ if s.attr&tui.Bold > 0 {
+ ret += "1;"
+ }
+ if s.attr&tui.Dim > 0 {
+ ret += "2;"
+ }
+ if s.attr&tui.Italic > 0 {
+ ret += "3;"
+ }
+ if s.attr&tui.Underline > 0 {
+ ret += "4;"
+ }
+ if s.attr&tui.Blink > 0 {
+ ret += "5;"
+ }
+ if s.attr&tui.Reverse > 0 {
+ ret += "7;"
+ }
+ ret += toAnsiString(s.fg, 30) + toAnsiString(s.bg, 40)
+
+ return "\x1b[" + strings.TrimSuffix(ret, ";") + "m"
+}
+
+func toAnsiString(color tui.Color, offset int) string {
+ col := int(color)
+ ret := ""
+ if col == -1 {
+ ret += strconv.Itoa(offset + 9)
+ } else if col < 8 {
+ ret += strconv.Itoa(offset + col)
+ } else if col < 16 {
+ ret += strconv.Itoa(offset - 30 + 90 + col - 8)
+ } else if col < 256 {
+ ret += fmt.Sprintf("%d;5;%d", offset+8, col)
+ } else if col >= (1 << 24) {
+ r := (col >> 16) & 0xff
+ g := (col >> 8) & 0xff
+ b := col & 0xff
+ ret += fmt.Sprintf("%d;2;%d;%d;%d", offset+8, r, g, b)
+ }
+ return ret + ";"
+}
+
var ansiRegex *regexp.Regexp
func init() {