Commit 6db2a890f26cf3133be1fed40c946ed5964a8ef3

Parents: 38df6d151fa06b8ea8ed0695c667d6608ffe04c3

From: Moritz Poldrack <git@moritz.sh>
Date: Thu Apr 7 14:31:14 2022 +0700

updated length to work with links and notifications

		

Stats

length.go +1/-1
length_test.go +60/-0

Changeset

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
diff --git a/length.go b/length.go
index 7f773235514b4e1dd311c54ee7a088a0deeb4f04..5c963b1e2487e5789e9731a2dcc68701f05a8894 100644
--- a/length.go
+++ b/length.go
@@ -6,6 +6,6 @@ 	"unicode/utf8"
 )
 
 func GetLengthWithoutCodes(content string) int {
-	var re = regexp.MustCompile(`(?m)\x1b\[([\d;]+m|[\d;]+(H|A|B|C|D|J|K|S|T)|s|u)`)
+	re := regexp.MustCompile(`(?m)\x1b(\[([\d;]+m|[\d;]+(H|A|B|C|D|J|K|S|T)|s|u)|\](8;;[^\x1b]*\x1b\\|777;notify;[^;]*;[^\a]*\a))`)
 	return utf8.RuneCountInString(re.ReplaceAllString(content, ""))
 }
diff --git a/length_test.go b/length_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..6103a7813352c520dafe525a213b4588d6b02661
--- /dev/null
+++ b/length_test.go
@@ -0,0 +1,60 @@
+package ansi
+
+import (
+	"fmt"
+	"testing"
+)
+
+func TestLength(t *testing.T) {
+	tests := []struct {
+		name           string
+		input          string
+		expectedLength int
+	}{
+		{
+			name:           "color",
+			input:          Blue("4444"),
+			expectedLength: 4,
+		},
+		{
+			name:           "formatting",
+			input:          Bold("88888888"),
+			expectedLength: 8,
+		},
+		{
+			name:           "link",
+			input:          LinkString("https://example.com", "333"),
+			expectedLength: 3,
+		},
+		{
+			name:           "notification",
+			input:          SendNotification("some title", "some body"),
+			expectedLength: 0,
+		},
+		{
+			name:           "movement",
+			input:          fmt.Sprintf("Up%s3x%s", Up(), UpX(400)),
+			expectedLength: 4,
+		},
+		{
+			name:           "cursor-save",
+			input:          fmt.Sprintf("Save%sRestore%s:)", SavePos(), RestorePos()),
+			expectedLength: 13,
+		},
+		{
+			name:           "clear-screen",
+			input:          fmt.Sprintf("clear%s", ClearScreen()),
+			expectedLength: 5,
+		},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			if l := GetLengthWithoutCodes(test.input); l != test.expectedLength {
+				t.Logf("expected length %d, but got %d", test.expectedLength, l)
+				fmt.Printf("%x", GetLengthWithoutCodes(test.input))
+				t.Fail()
+			}
+		})
+	}
+}