Debian Codegraph @

width.go

raw symbols SCIP
1 package displaywidth
2
3 import (
4 "unicode/utf8"
5
6 "github.com/clipperhouse/uax29/v2/graphemes"
7 )
8
9 // String calculates the display width of a string,
10 // by iterating over grapheme clusters in the string
11 // and summing their widths.
12 func String(s string) int {
13 return DefaultOptions.String(s)
14 }
15
16 // String calculates the display width of a string, for the given options, by
17 // iterating over grapheme clusters in the string and summing their widths.
18 func (options Options) String(s string) int {
19 width := 0
20 pos := 0
21
22 for pos < len(s) {
23 // Try ASCII optimization
24 asciiLen := printableASCIILength(s[pos:])
25 if asciiLen > 0 {
26 width += asciiLen
27 pos += asciiLen
28 continue
29 }
30
31 // Not ASCII, use grapheme parsing
32 g := graphemes.FromString(s[pos:])
33 g.AnsiEscapeSequences = options.ControlSequences
34 g.AnsiEscapeSequences8Bit = options.ControlSequences8Bit
35
36 start := pos
37
38 for g.Next() {
39 v := g.Value()
40 width += graphemeWidth(v, options)
41 pos += len(v)
42
43 // Quick check: if remaining might have printable ASCII, break to outer loop
44 if pos < len(s) && s[pos] >= 0x20 && s[pos] <= 0x7E {
45 break
46 }
47 }
48
49 // Defensive, should not happen: if no progress was made,
50 // skip a byte to prevent infinite loop. Only applies if
51 // the grapheme parser misbehaves.
52 if pos == start {
53 pos++
54 }
55 }
56
57 return width
58 }
59
60 // Bytes calculates the display width of a []byte,
61 // by iterating over grapheme clusters in the byte slice
62 // and summing their widths.
63 func Bytes(s []byte) int {
64 return DefaultOptions.Bytes(s)
65 }
66
67 // Bytes calculates the display width of a []byte, for the given options, by
68 // iterating over grapheme clusters in the slice and summing their widths.
69 func (options Options) Bytes(s []byte) int {
70 width := 0
71 pos := 0
72
73 for pos < len(s) {
74 // Try ASCII optimization
75 asciiLen := printableASCIILength(s[pos:])
76 if asciiLen > 0 {
77 width += asciiLen
78 pos += asciiLen
79 continue
80 }
81
82 // Not ASCII, use grapheme parsing
83 g := graphemes.FromBytes(s[pos:])
84 g.AnsiEscapeSequences = options.ControlSequences
85 g.AnsiEscapeSequences8Bit = options.ControlSequences8Bit
86
87 start := pos
88
89 for g.Next() {
90 v := g.Value()
91 width += graphemeWidth(v, options)
92 pos += len(v)
93
94 // Quick check: if remaining might have printable ASCII, break to outer loop
95 if pos < len(s) && s[pos] >= 0x20 && s[pos] <= 0x7E {
96 break
97 }
98 }
99
100 // Defensive, should not happen: if no progress was made,
101 // skip a byte to prevent infinite loop. Only applies if
102 // the grapheme parser misbehaves.
103 if pos == start {
104 pos++
105 }
106 }
107
108 return width
109 }
110
111 // Rune calculates the display width of a rune. You
112 // should almost certainly use [String] or [Bytes] for
113 // most purposes.
114 //
115 // The smallest unit of display width is a grapheme
116 // cluster, not a rune. Iterating over runes to measure
117 // width is incorrect in many cases.
118 func Rune(r rune) int {
119 return DefaultOptions.Rune(r)
120 }
121
122 // Rune calculates the display width of a rune, for the given options.
123 //
124 // You should almost certainly use [String] or [Bytes] for most purposes.
125 //
126 // The smallest unit of display width is a grapheme cluster, not a rune.
127 // Iterating over runes to measure width is incorrect in many cases.
128 func (options Options) Rune(r rune) int {
129 if r < utf8.RuneSelf {
130 return asciiWidth(byte(r))
131 }
132
133 // Surrogates (U+D800-U+DFFF) are invalid UTF-8.
134 if r >= 0xD800 && r <= 0xDFFF {
135 return 0
136 }
137
138 var buf [4]byte
139 n := utf8.EncodeRune(buf[:], r)
140
141 // Skip the grapheme iterator
142 return graphemeWidth(buf[:n], options)
143 }
144
145 const _Default property = 0
146
147 // graphemeWidth returns the display width of a grapheme cluster.
148 // The passed string must be a single grapheme cluster.
149 func graphemeWidth[T ~string | []byte](s T, options Options) int {
150 if len(s) == 0 {
151 return 0
152 }
153
154 // C1 controls (0x80-0x9F) are zero-width when 8-bit control sequences
155 // are enabled. This must be checked before the single-byte optimization
156 // below, which would otherwise return width 1 for these bytes.
157 if options.ControlSequences8Bit && s[0] >= 0x80 && s[0] <= 0x9F {
158 return 0
159 }
160
161 // Optimization: single-byte graphemes need no property lookup
162 if len(s) == 1 {
163 return asciiWidth(s[0])
164 }
165
166 // Multi-byte grapheme clusters led by a C0 control (0x00-0x1F)
167 if s[0] <= 0x1F {
168 return 0
169 }
170
171 p, sz := lookup(s)
172 prop := property(p)
173
174 // Variation Selector 16 (VS16) requests emoji presentation
175 if prop != _Wide && sz > 0 && len(s) >= sz+3 {
176 vs := s[sz : sz+3]
177 if isVS16(vs) {
178 prop = _Wide
179 }
180 // VS15 (0x8E) requests text presentation but does not affect width,
181 // in my reading of Unicode TR51. Falls through to return the base
182 // character's property.
183 }
184
185 if options.EastAsianWidth && prop == _East_Asian_Ambiguous {
186 prop = _Wide
187 }
188
189 if prop > upperBound {
190 prop = _Default
191 }
192
193 return propertyWidths[prop]
194 }
195
196 func asciiWidth(b byte) int {
197 if b <= 0x1F || b == 0x7F {
198 return 0
199 }
200 return 1
201 }
202
203 // printableASCIILength returns the length of consecutive printable ASCII bytes
204 // starting at the beginning of s.
205 func printableASCIILength[T string | []byte](s T) int {
206 i := 0
207 for ; i < len(s); i++ {
208 b := s[i]
209 // Printable ASCII is 0x20-0x7E (space through tilde)
210 if b < 0x20 || b > 0x7E {
211 break
212 }
213 }
214
215 // If the next byte is non-ASCII (>= 0x80), back off by 1. The grapheme
216 // parser may group the last ASCII byte with subsequent non-ASCII bytes,
217 // such as combining marks.
218 if i > 0 && i < len(s) && s[i] >= 0x80 {
219 i--
220 }
221
222 return i
223 }
224
225 // isVS16 checks if the slice matches VS16 (U+FE0F) UTF-8 encoding
226 // (EF B8 8F). It assumes len(s) >= 3.
227 func isVS16[T ~string | []byte](s T) bool {
228 return s[0] == 0xEF && s[1] == 0xB8 && s[2] == 0x8F
229 }
230
231 // propertyWidths is a jump table of sorts, instead of a switch
232 var propertyWidths = [4]int{
233 _Default: 1,
234 _Zero_Width: 0,
235 _Wide: 2,
236 _East_Asian_Ambiguous: 1,
237 }
238
239 const upperBound = property(len(propertyWidths) - 1)