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

support ANSI OSC escapes as well as CSI colors #220

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
24 changes: 23 additions & 1 deletion util.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,29 @@ import (
"github.com/mattn/go-runewidth"
)

var ansi = regexp.MustCompile("\033\\[(?:[0-9]{1,3}(?:;[0-9]{1,3})*)?[m|K]")
var ansi = generateEscapeFilterRegex()

// generateEscapeFilterRegex builds a regex to remove non-printing ANSI escape codes from strings so
// that their display width can be determined accurately. The regex is complicated enough that it's
// better to build it programmatically than to write it by hand.
// Based on https://en.wikipedia.org/wiki/ANSI_escape_code#Fe_Escape_sequences
func generateEscapeFilterRegex() *regexp.Regexp {
var regESC = "\x1b" // ASCII escape
var regBEL = "\x07" // ASCII bell

// String Terminator - ends ANSI sequences
var regST = "(" + regESC + "\\\\" + "|" + regBEL + ")"

// Control Sequence Introducer - usually color codes
// esc + [ + zero or more 0x30-0x3f + zero or more 0x20-0x2f and a single 0x40-0x7e
var regCSI = regESC + "\\[" + "[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]"

// Operating System Command - hyperlinks
// esc + ] + any number of any chars + ST
var regOSC = regESC + "\\]" + ".*?" + regST

return regexp.MustCompile("(" + regCSI + "|" + regOSC + ")")
}

func DisplayWidth(str string) int {
return runewidth.StringWidth(ansi.ReplaceAllLiteralString(str, ""))
Expand Down
3 changes: 3 additions & 0 deletions wrap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ func TestDisplayWidth(t *testing.T) {
}
input = "\033[43;30m" + input + "\033[00m"
checkEqual(t, DisplayWidth(input), want)

input = "\033]8;;https://github.com/olekukonko/tablewriter/pull/220\033\\Github PR\033]8;;\033\\"
checkEqual(t, DisplayWidth(input), 9)
}

// WrapString was extremely memory greedy, it performed insane number of
Expand Down