~poldi1405/go-ansi

ref: 38df6d151fa06b8ea8ed0695c667d6608ffe04c3 go-ansi/strip.go -rw-r--r-- 1.8 KiB
38df6d15 — Moritz Poldrack expanded strip for notifications 4 months ago
                                                                                
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
79
80
81
82
package ansi

import (
	"bytes"
	"fmt"
)

// StripString removes all ANSI-Escape sequences from the given string and
// returns the cleaned version
func StripString(str string) string {
	bts := []byte(str)
	bts = stripStandard(bts)
	bts = stripLink(bts)
	bts = stripNotify(bts)

	return string(bts)
}

func stripNotify(bts []byte) []byte {
	for {
		index := bytes.Index(bts, []byte{0x1b, ']', '7', '7', '7', ';'})
		if index == -1 {
			break
		}
		removeUntil := bytes.Index(bts[index+1:], []byte{0x07})
		if removeUntil == -1 {
			break
		}

		bts = append(bts[:index], bts[index+removeUntil+2:]...)
	}

	return bts
}

func stripLink(bts []byte) []byte {
	for { // stop if the last run did not match anything
		index := bytes.Index(bts, []byte{0x1b, '\\'})
		if index == -1 {
			break
		}
		removeUntil := bytes.Index(bts[index+1:], []byte{0x1b})
		if removeUntil == -1 {
			break
		}

		bts = append(bts[:index], bts[index+removeUntil+1:]...)
	}
	bts = bytes.ReplaceAll(bts, []byte{0x1b, ']', '8', ';', ';', 0x1b, '\\'}, []byte{})
	bts = bytes.ReplaceAll(bts, []byte{0x1b, ']', '8', ';', ';'}, []byte{})
	return bts
}

func stripStandard(bts []byte) []byte {
	matched := true
	for matched { // stop if the last run did not match anything
		index := bytes.Index(bts, []byte{0x1b, '['})
		if index == -1 {
			break
		}
		removeUntil := index + 2
		for i := removeUntil; i < len(bts); i++ {
			if (bts[i] >= 0x30 && bts[i] <= 0x39) || bts[i] == 0x3b {
				removeUntil++
				continue
			}
			if (bts[i] >= 0x41 && bts[i] <= 0x5a) || (bts[i] >= 0x61 && bts[i] <= 0x7a) {
				removeUntil++
				break
			}
			// we shouldn't be here in valid codes. anyway. stop
			// what we're doing before be break something
			fmt.Print("oppsie! ")
			fmt.Println(bts[index:removeUntil])
			matched = false
			break
		}

		bts = append(bts[:index], bts[removeUntil:]...)
	}
	return bts
}