ansi.go
This file
Path
src/ansi.go
578 lines · 13.1 KiB · Go
Last changed by
Clean up non-ascii charactersJunegunn Choibefore adoption8b66489
History of this fileTake it
The walk stopped after 200 commits: lines older than 76efddd point at it.
bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 1–486why, one step back1package fzf23import (4 "fmt"5 "strconv"6 "strings"7 "unicode/utf8"89 "github.com/junegunn/fzf/src/algo"10 "github.com/junegunn/fzf/src/tui"11)1213type ansiOffset struct {14 offset [2]int3215 color ansiState16}1718type url struct {19 uri string20 params string21}2223type ansiState struct {24 fg tui.Color25 bg tui.Color26 ul tui.Color27 attr tui.Attr28 lbg tui.Color29 url *url30}3132func (s *ansiState) colored() bool {33 return s.fg != -1 || s.bg != -1 || s.ul != -1 || s.attr > 0 || s.lbg >= 0 || s.url != nil34}3536func (s *ansiState) equals(t *ansiState) bool {37 if t == nil {38 return !s.colored()39 }40 return s.fg == t.fg && s.bg == t.bg && s.ul == t.ul && s.attr == t.attr && s.lbg == t.lbg && s.url == t.url41}4243func (s *ansiState) ToString() string {44 if !s.colored() {45 return ""46 }4748 ret := ""49 if s.attr&tui.Bold > 0 || s.attr&tui.BoldForce > 0 {50 ret += "1;"51 }52 if s.attr&tui.Dim > 0 {53 ret += "2;"54 }55 if s.attr&tui.Italic > 0 {56 ret += "3;"57 }58 if s.attr&tui.Underline > 0 {59 switch s.attr.UnderlineStyle() {60 case tui.UlStyleDouble:61 ret += "4:2;"62 case tui.UlStyleCurly:63 ret += "4:3;"64 case tui.UlStyleDotted:65 ret += "4:4;"66 case tui.UlStyleDashed:67 ret += "4:5;"68 default:69 ret += "4;"70 }71 }72 if s.attr&tui.Blink > 0 {73 ret += "5;"74 }75 if s.attr&tui.Reverse > 0 {76 ret += "7;"77 }78 if s.attr&tui.StrikeThrough > 0 {79 ret += "9;"80 }81 ret += toAnsiString(s.fg, 30) + toAnsiString(s.bg, 40)82 if s.ul != -1 {83 ret += toAnsiStringUl(s.ul)84 }8586 ret = "\x1b[" + strings.TrimSuffix(ret, ";") + "m"87 if s.url != nil {88 ret = fmt.Sprintf("\x1b]8;%s;%s\x1b\\%s\x1b]8;;\x1b", s.url.params, s.url.uri, ret)89 }90 return ret91}9293func toAnsiStringUl(color tui.Color) string {94 col := int(color)95 if col < 0 {96 return ""97 }98 if col >= (1 << 24) {99 r := strconv.Itoa((col >> 16) & 0xff)100 g := strconv.Itoa((col >> 8) & 0xff)101 b := strconv.Itoa(col & 0xff)102 return "58;2;" + r + ";" + g + ";" + b + ";"103 }104 return "58;5;" + strconv.Itoa(col) + ";"105}106107func toAnsiString(color tui.Color, offset int) string {108 col := int(color)109 ret := ""110 if col == -1 {111 ret += strconv.Itoa(offset + 9)112 } else if col < 8 {113 ret += strconv.Itoa(offset + col)114 } else if col < 16 {115 ret += strconv.Itoa(offset - 30 + 90 + col - 8)116 } else if col < 256 {117 ret += strconv.Itoa(offset+8) + ";5;" + strconv.Itoa(col)118 } else if col >= (1 << 24) {119 r := strconv.Itoa((col >> 16) & 0xff)120 g := strconv.Itoa((col >> 8) & 0xff)121 b := strconv.Itoa(col & 0xff)122 ret += strconv.Itoa(offset+8) + ";2;" + r + ";" + g + ";" + b123 }124 return ret + ";"125}126127func matchOperatingSystemCommand(s string, start int) int {128 // `\x1b][0-9][;:][[:print:]]+(?:\x1b\\\\|\x07)`129 // ^ match starting here after the first printable character130 //131 i := start // prefix matched in nextAnsiEscapeSequence()132133 // Find the terminator: BEL (\x07) or ESC (\x1b) for ST (\x1b\\)134 idx := algo.IndexByteTwo(stringBytes(s[i:]), '\x07', '\x1b')135 if idx < 0 {136 return -1137 }138 i += idx139140 if s[i] == '\x07' {141 return i + 1142 }143 // `\x1b]8;PARAMS;URI\x1b\\TITLE\x1b]8;;\x1b`144 // ------145 if i < len(s)-1 && s[i+1] == '\\' {146 return i + 2147 }148149 // `\x1b]8;PARAMS;URI\x1b\\TITLE\x1b]8;;\x1b`150 // ------------151 if s[:i+1] == "\x1b]8;;\x1b" {152 return i + 1153 }154155 return -1156}157158func matchControlSequence(s string) int {159 // `\x1b[\\[()][0-9;:?]*[a-zA-Z@]`160 // ^ match starting here161 //162 i := 2 // prefix matched in nextAnsiEscapeSequence()163 for ; i < len(s); i++ {164 c := s[i]165 switch c {166 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ';', ':', '?':167 // ok168 default:169 if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '@' {170 return i + 1171 }172 return -1173 }174 }175 return -1176}177178func isCtrlSeqStart(c uint8) bool {179 switch c {180 case '\\', '[', '(', ')':181 return true182 }183 return false184}185186// nextAnsiEscapeSequence returns the ANSI escape sequence and is equivalent to187// calling FindStringIndex() on the below regex (which was originally used):188//189// "(?:\x1b[\\[()][0-9;:?]*[a-zA-Z@]|\x1b][0-9]+[;:][[:print:]]+(?:\x1b\\\\|\x07)|\x1b.|[\x0e\x0f]|.\x08|\n)"190func nextAnsiEscapeSequence(s string) (int, int) {191 // fast check for ANSI escape sequences192 i := 0193 for ; i < len(s); i++ {194 switch s[i] {195 case '\x0e', '\x0f', '\x1b', '\x08', '\n':196 // We ignore the fact that '\x08' cannot be the first char197 // in the string and be an escape sequence for the sake of198 // speed and simplicity.199 goto Loop200 }201 }202 return -1, -1203204Loop:205 for ; i < len(s); i++ {206 switch s[i] {207 case '\n':208 // match: `\n`209 return i, i + 1210 case '\x08':211 // backtrack to match: `.\x08`212 if i > 0 && s[i-1] != '\n' {213 if s[i-1] < utf8.RuneSelf {214 return i - 1, i + 1215 }216 _, n := utf8.DecodeLastRuneInString(s[:i])217 return i - n, i + 1218 }219 case '\x1b':220 // match: `\x1b[\\[()][0-9;:?]*[a-zA-Z@]`221 if i+2 < len(s) && isCtrlSeqStart(s[i+1]) {222 if j := matchControlSequence(s[i:]); j != -1 {223 return i, i + j224 }225 }226227 // match: `\x1b][0-9]+[;:][[:print:]]+(?:\x1b\\\\|\x07)`228 if i+5 < len(s) && s[i+1] == ']' {229 j := 2230 // \x1b][0-9]+[;:][[:print:]]+(?:\x1b\\\\|\x07)231 // ------232 for ; i+j < len(s) && isNumeric(s[i+j]); j++ {233 }234235 // \x1b][0-9]+[;:][[:print:]]+(?:\x1b\\\\|\x07)236 // ---------------237 if j > 2 && i+j+1 < len(s) && (s[i+j] == ';' || s[i+j] == ':') && s[i+j+1] >= '\x20' {238 if k := matchOperatingSystemCommand(s[i:], j+2); k != -1 {239 return i, i + k240 }241 }242 }243244 // match: `\x1b.`245 if i+1 < len(s) && s[i+1] != '\n' {246 if s[i+1] < utf8.RuneSelf {247 return i, i + 2248 }249 _, n := utf8.DecodeRuneInString(s[i+1:])250 return i, i + n + 1251 }252 case '\x0e', '\x0f':253 // match: `[\x0e\x0f]`254 return i, i + 1255 }256 }257 return -1, -1258}259260func extractColor(str string, state *ansiState, proc func(string, *ansiState) bool) (string, *[]ansiOffset, *ansiState) {261 // We append to a stack allocated variable that we'll262 // later copy and return, to save on allocations.263 offsets := make([]ansiOffset, 0, 32)264265 if state != nil {266 offsets = append(offsets, ansiOffset{[2]int32{0, 0}, *state})267 }268269 var (270 pstate *ansiState // lazily allocated271 output strings.Builder272 prevIdx int273 runeCount int274 )275 for idx := 0; idx < len(str); {276 // Make sure that we found an ANSI code277 start, end := nextAnsiEscapeSequence(str[idx:])278 if start == -1 {279 break280 }281 start += idx282 idx += end283284 // Check if we should continue285 prev := str[prevIdx:start]286 if proc != nil && !proc(prev, state) {287 return "", nil, nil288 }289 prevIdx = idx290291 if len(prev) != 0 {292 runeCount += utf8.RuneCountInString(prev)293 // Grow the buffer size to the maximum possible length (string length294 // containing ansi codes) to avoid repetitive allocation295 if output.Cap() == 0 {296 output.Grow(len(str))297 }298 output.WriteString(prev)299 }300301 code := str[start:idx]302 newState := interpretCode(code, state)303 if code == "\n" || !newState.equals(state) {304 if state != nil {305 // Update last offset306 (&offsets[len(offsets)-1]).offset[1] = int32(runeCount)307 }308309 if code == "\n" {310 output.WriteRune('\n')311 runeCount++312 // Full-background marker313 if newState.lbg >= 0 {314 marker := newState315 marker.attr |= tui.FullBg316 offsets = append(offsets, ansiOffset{317 [2]int32{int32(runeCount), int32(runeCount)},318 marker,319 })320 // Reset the full-line background color321 newState.lbg = -1322 }323 }324325 if newState.colored() {326 // Append new offset327 if pstate == nil {328 pstate = &ansiState{}329 }330 *pstate = newState331 state = pstate332 offsets = append(offsets, ansiOffset{333 [2]int32{int32(runeCount), int32(runeCount)},334 newState,335 })336 } else {337 // Discard state338 state = nil339 }340 }341 }342343 var rest string344 var trimmed string345 if prevIdx == 0 {346 // No ANSI code found347 rest = str348 trimmed = str349 } else {350 rest = str[prevIdx:]351 output.WriteString(rest)352 trimmed = output.String()353 }354 if proc != nil {355 proc(rest, state)356 }357 if len(offsets) > 0 {358 if len(rest) > 0 && state != nil {359 // Update last offset360 runeCount += utf8.RuneCountInString(rest)361 (&offsets[len(offsets)-1]).offset[1] = int32(runeCount)362 }363 // Return a copy of the offsets slice364 a := make([]ansiOffset, len(offsets))365 copy(a, offsets)366 return trimmed, &a, state367 }368 return trimmed, nil, state369}370371func parseAnsiCode(s string) (int, byte, string) {372 var remaining string373 var sep byte374 // Find the first separator (either ; or :)375 i := -1376 for j := 0; j < len(s); j++ {377 if s[j] == ';' || s[j] == ':' {378 i = j379 break380 }381 }382 if i >= 0 {383 sep = s[i]384 remaining = s[i+1:]385 s = s[:i]386 }387388 if len(s) > 0 {389 // Inlined version of strconv.Atoi() that only handles positive390 // integers and does not allocate on error.391 code := 0392 for _, ch := range stringBytes(s) {393 ch -= '0'394 if ch > 9 {395 return -1, sep, remaining396 }397 code = code*10 + int(ch)398 }399 return code, sep, remaining400 }401402 return -1, sep, remaining403}404405func interpretCode(ansiCode string, prevState *ansiState) ansiState {406 if ansiCode == "\n" {407 if prevState != nil {408 return *prevState409 }410 return ansiState{-1, -1, -1, 0, -1, nil}411 }412413 var state ansiState414 if prevState == nil {415 state = ansiState{-1, -1, -1, 0, -1, nil}416 } else {417 state = ansiState{prevState.fg, prevState.bg, prevState.ul, prevState.attr, prevState.lbg, prevState.url}418 }419 if ansiCode[0] != '\x1b' || ansiCode[1] != '[' || ansiCode[len(ansiCode)-1] != 'm' {420 if prevState != nil && (strings.HasSuffix(ansiCode, "0K") || strings.HasSuffix(ansiCode, "[K")) {421 state.lbg = prevState.bg422 } else if strings.HasPrefix(ansiCode, "\x1b]8;") && (strings.HasSuffix(ansiCode, "\x1b\\") || strings.HasSuffix(ansiCode, "\a")) {423 stLen := 2424 if strings.HasSuffix(ansiCode, "\a") {425 stLen = 1426 }427 // "\x1b]8;;\x1b\\" or "\x1b]8;;\a"428 if len(ansiCode) == 5+stLen && ansiCode[4] == ';' {429 state.url = nil430 } else if paramsEnd := strings.IndexRune(ansiCode[4:], ';'); paramsEnd >= 0 {431 params := ansiCode[4 : 4+paramsEnd]432 uri := ansiCode[5+paramsEnd : len(ansiCode)-stLen]433 state.url = &url{uri: uri, params: params}434 }435 }436 return state437 }438439 reset := func() {440 state.fg = -1441 state.bg = -1442 state.ul = -1443 state.attr = 0444 }445446 if len(ansiCode) <= 3 {447 reset()448 return state449 }450 ansiCode = ansiCode[2 : len(ansiCode)-1]451452 state256 := 0453 ptr := &state.fg454455 count := 0456 for len(ansiCode) != 0 {457 var num int458 var sep byte459 if num, sep, ansiCode = parseAnsiCode(ansiCode); num != -1 {460 count++461 switch state256 {462 case 0:463 switch num {464 case 38:465 ptr = &state.fg466 state256++467 case 48:468 ptr = &state.bg469 state256++470 case 58:471 ptr = &state.ul472 state256++473 case 39:474 state.fg = -1475 case 49:476 state.bg = -1477 case 59:478 state.ul = -1479 case 1:480 state.attr = state.attr | tui.Bold481 case 2:482 state.attr = state.attr | tui.Dim483 case 3:484 state.attr = state.attr | tui.Italic485 case 4:486 if sep == ':' {Clean up non-ascii charactersJunegunn Choibefore adoption8b66489
line 487why, one step back487 // SGR 4:N - underline style sub-parameterbash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 488–578why, one step back488 var subNum int489 subNum, _, ansiCode = parseAnsiCode(ansiCode)490 state.attr = state.attr &^ tui.UnderlineStyleMask491 switch subNum {492 case 0:493 state.attr = state.attr &^ tui.Underline494 case 1:495 state.attr = state.attr | tui.Underline496 case 2:497 state.attr = state.attr | tui.Underline | tui.UlStyleDouble498 case 3:499 state.attr = state.attr | tui.Underline | tui.UlStyleCurly500 case 4:501 state.attr = state.attr | tui.Underline | tui.UlStyleDotted502 case 5:503 state.attr = state.attr | tui.Underline | tui.UlStyleDashed504 default:505 state.attr = state.attr | tui.Underline506 }507 } else {508 state.attr = state.attr | tui.Underline509 }510 case 5:511 state.attr = state.attr | tui.Blink512 case 7:513 state.attr = state.attr | tui.Reverse514 case 9:515 state.attr = state.attr | tui.StrikeThrough516 case 22:517 state.attr = state.attr &^ tui.Bold518 state.attr = state.attr &^ tui.Dim519 case 23: // tput rmso520 state.attr = state.attr &^ tui.Italic521 case 24: // tput rmul522 state.attr = state.attr &^ tui.Underline523 state.attr = state.attr &^ tui.UnderlineStyleMask524 case 25:525 state.attr = state.attr &^ tui.Blink526 case 27:527 state.attr = state.attr &^ tui.Reverse528 case 29:529 state.attr = state.attr &^ tui.StrikeThrough530 case 0:531 reset()532 state256 = 0533 default:534 if num >= 30 && num <= 37 {535 state.fg = tui.Color(num - 30)536 } else if num >= 40 && num <= 47 {537 state.bg = tui.Color(num - 40)538 } else if num >= 90 && num <= 97 {539 state.fg = tui.Color(num - 90 + 8)540 } else if num >= 100 && num <= 107 {541 state.bg = tui.Color(num - 100 + 8)542 }543 }544 case 1:545 switch num {546 case 2:547 state256 = 10 // MAGIC548 case 5:549 state256++550 default:551 state256 = 0552 }553 case 2:554 *ptr = tui.Color(num)555 state256 = 0556 case 10:557 *ptr = tui.Color(1<<24) | tui.Color(num<<16)558 state256++559 case 11:560 *ptr = *ptr | tui.Color(num<<8)561 state256++562 case 12:563 *ptr = *ptr | tui.Color(num)564 state256 = 0565 }566 }567 }568569 // Empty sequence: reset570 if count == 0 {571 reset()572 }573574 if state256 > 0 {575 *ptr = -1576 }577 return state578}