Debian Codegraph @

runewidth.go

raw
1 package runewidth
2
3 import (
4 "os"
5 "sort"
6 "strings"
7 "unicode/utf8"
8
9 "github.com/clipperhouse/uax29/v2/graphemes"
10 )
11
12 //go:generate go run script/generate.go
13
14 var (
15 // EastAsianWidth will be set true if the current locale is CJK
16 EastAsianWidth bool
17
18 // StrictEmojiNeutral should be set false if handle broken fonts
19 StrictEmojiNeutral bool = true
20
21 // ZeroWidthJoiner is flag to set to use UTR#51 ZWJ.
22 //
23 // Deprecated: ZWJ sequences are always handled through Unicode
24 // grapheme cluster segmentation now, so this flag has no effect.
25 // It is kept only for compatibility with code written against
26 // v0.0.9 and earlier.
27 ZeroWidthJoiner bool
28
29 // DefaultCondition is a condition in current locale
30 DefaultCondition = &Condition{
31 EastAsianWidth: false,
32 StrictEmojiNeutral: true,
33 }
34 )
35
36 var (
37 zerowidth table // combining + nonprint merged for faster zero-width lookup
38 widewidth table // ambiguous + doublewidth merged for EA path
39 eastAsianWidth widthTable
40 eastAsianWidth0 [0x300]byte
41 strictWidthLUT [2][0x110000]byte
42 )
43
44 func init() {
45 zerowidth = mergeIntervals(combining, nonprint)
46 widewidth = mergeIntervals(ambiguous, doublewidth)
47 eastAsianWidth = makeWidthTable(zerowidth, widewidth)
48 for r := range eastAsianWidth0 {
49 eastAsianWidth0[r] = byte(runeWidthEastAsianNoCache(rune(r), true))
50 }
51 initStrictWidthLUT()
52 handleEnv()
53 }
54
55 func mergeIntervals(t1, t2 table) table {
56 merged := make(table, 0, len(t1)+len(t2))
57 i, j := 0, 0
58 for i < len(t1) && j < len(t2) {
59 if t1[i].first <= t2[j].first {
60 merged = append(merged, t1[i])
61 i++
62 } else {
63 merged = append(merged, t2[j])
64 j++
65 }
66 }
67 merged = append(merged, t1[i:]...)
68 merged = append(merged, t2[j:]...)
69 if len(merged) == 0 {
70 return merged
71 }
72 result := merged[:1]
73 for _, iv := range merged[1:] {
74 last := &result[len(result)-1]
75 if iv.first <= last.last+1 {
76 if iv.last > last.last {
77 last.last = iv.last
78 }
79 } else {
80 result = append(result, iv)
81 }
82 }
83 return result
84 }
85
86 func handleEnv() {
87 env := os.Getenv("RUNEWIDTH_EASTASIAN")
88 if env == "" {
89 EastAsianWidth = IsEastAsian()
90 } else {
91 EastAsianWidth = env == "1"
92 }
93 // update DefaultCondition
94 if DefaultCondition.EastAsianWidth != EastAsianWidth {
95 DefaultCondition.EastAsianWidth = EastAsianWidth
96 if len(DefaultCondition.combinedLut) > 0 {
97 DefaultCondition.combinedLut = DefaultCondition.combinedLut[:0]
98 CreateLUT()
99 }
100 }
101 }
102
103 type interval struct {
104 first rune
105 last rune
106 }
107
108 type table []interval
109
110 type widthInterval struct {
111 first rune
112 last rune
113 width byte
114 }
115
116 type widthTable []widthInterval
117
118 func inTable(r rune, t table) bool {
119 if r < t[0].first {
120 return false
121 }
122 if r > t[len(t)-1].last {
123 return false
124 }
125
126 bot := 0
127 top := len(t) - 1
128 for top >= bot {
129 mid := (bot + top) >> 1
130
131 switch {
132 case t[mid].last < r:
133 bot = mid + 1
134 case t[mid].first > r:
135 top = mid - 1
136 default:
137 return true
138 }
139 }
140
141 return false
142 }
143
144 func makeWidthTable(zero, two table) widthTable {
145 wt := make(widthTable, 0, len(zero)+len(two))
146 zi := 0
147 for _, iv := range two {
148 start := iv.first
149 for zi < len(zero) && zero[zi].last < start {
150 zi++
151 }
152 for i := zi; i < len(zero) && zero[i].first <= iv.last; i++ {
153 if start < zero[i].first {
154 wt = append(wt, widthInterval{start, zero[i].first - 1, 2})
155 }
156 if start <= zero[i].last {
157 start = zero[i].last + 1
158 }
159 if start > iv.last {
160 break
161 }
162 }
163 if start <= iv.last {
164 wt = append(wt, widthInterval{start, iv.last, 2})
165 }
166 }
167 for _, iv := range zero {
168 wt = append(wt, widthInterval{iv.first, iv.last, 0})
169 }
170 sort.Slice(wt, func(i, j int) bool {
171 return wt[i].first < wt[j].first
172 })
173 return wt
174 }
175
176 func inWidthTable(r rune, t widthTable) (int, bool) {
177 if r < t[0].first {
178 return 0, false
179 }
180 if r > t[len(t)-1].last {
181 return 0, false
182 }
183
184 bot := 0
185 top := len(t) - 1
186 for top >= bot {
187 mid := (bot + top) >> 1
188
189 switch {
190 case t[mid].last < r:
191 bot = mid + 1
192 case t[mid].first > r:
193 top = mid - 1
194 default:
195 return int(t[mid].width), true
196 }
197 }
198
199 return 0, false
200 }
201
202 func runeWidthNoLUT(r rune, eastAsian, strictEmojiNeutral bool) int {
203 if !eastAsian {
204 if r < 0x20 {
205 return 0
206 }
207 if (r >= 0x7F && r <= 0x9F) || r == 0xAD { // nonprint
208 return 0
209 }
210 if r < 0x300 {
211 return 1
212 }
213 switch {
214 case inTable(r, zerowidth):
215 return 0
216 case inTable(r, doublewidth):
217 return 2
218 default:
219 return 1
220 }
221 }
222
223 if r < 0x300 {
224 return int(eastAsianWidth0[r])
225 }
226 if w, ok := inWidthTable(r, eastAsianWidth); ok {
227 return w
228 }
229 if !strictEmojiNeutral && inTable(r, emoji) {
230 return 2
231 }
232 return 1
233 }
234
235 func runeWidthEastAsianNoCache(r rune, strictEmojiNeutral bool) int {
236 if w, ok := inWidthTable(r, eastAsianWidth); ok {
237 return w
238 }
239 if !strictEmojiNeutral && inTable(r, emoji) {
240 return 2
241 }
242 return 1
243 }
244
245 func initStrictWidthLUT() {
246 for i := range strictWidthLUT[0] {
247 r := rune(i)
248 strictWidthLUT[0][i] = byte(runeWidthNoLUT(r, false, true))
249 strictWidthLUT[1][i] = byte(runeWidthNoLUT(r, true, true))
250 }
251 }
252
253 var private = table{
254 {0x00E000, 0x00F8FF}, {0x0F0000, 0x0FFFFD}, {0x100000, 0x10FFFD},
255 }
256
257 var nonprint = table{
258 {0x0000, 0x001F}, {0x007F, 0x009F}, {0x00AD, 0x00AD},
259 {0x070F, 0x070F}, {0x180B, 0x180E}, {0x200B, 0x200F},
260 {0x2028, 0x202E}, {0x206A, 0x206F}, {0xD800, 0xDFFF},
261 {0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFB}, {0xFFFE, 0xFFFF},
262 }
263
264 // Condition have flag EastAsianWidth whether the current locale is CJK or not.
265 type Condition struct {
266 combinedLut []byte
267 EastAsianWidth bool
268 StrictEmojiNeutral bool
269
270 // Deprecated: ZWJ sequences are always handled through Unicode
271 // grapheme cluster segmentation now, so this flag has no effect.
272 // It is kept only for compatibility with code written against
273 // v0.0.9 and earlier.
274 ZeroWidthJoiner bool
275 }
276
277 // NewCondition return new instance of Condition which is current locale.
278 func NewCondition() *Condition {
279 return &Condition{
280 EastAsianWidth: EastAsianWidth,
281 StrictEmojiNeutral: StrictEmojiNeutral,
282 ZeroWidthJoiner: ZeroWidthJoiner,
283 }
284 }
285
286 // RuneWidth returns the number of cells in r.
287 // See http://www.unicode.org/reports/tr11/
288 func (c *Condition) RuneWidth(r rune) int {
289 if r < 0 || r > 0x10FFFF {
290 return 0
291 }
292 if len(c.combinedLut) > 0 {
293 return int(c.combinedLut[r>>1]>>(uint(r&1)*4)) & 3
294 }
295 if c.StrictEmojiNeutral {
296 if c.EastAsianWidth {
297 return int(strictWidthLUT[1][r])
298 }
299 return int(strictWidthLUT[0][r])
300 }
301 return runeWidthNoLUT(r, c.EastAsianWidth, c.StrictEmojiNeutral)
302 }
303
304 // CreateLUT will create an in-memory lookup table of 557056 bytes for faster operation.
305 // This should not be called concurrently with other operations on c.
306 // If options in c is changed, CreateLUT should be called again.
307 func (c *Condition) CreateLUT() {
308 const max = 0x110000
309 lut := c.combinedLut
310 if len(c.combinedLut) != 0 {
311 // Remove so we don't use it.
312 c.combinedLut = nil
313 } else {
314 lut = make([]byte, max/2)
315 }
316 for i := range lut {
317 i32 := int32(i * 2)
318 x0 := c.RuneWidth(i32)
319 x1 := c.RuneWidth(i32 + 1)
320 lut[i] = uint8(x0) | uint8(x1)<<4
321 }
322 c.combinedLut = lut
323 }
324
325 // graphemeWidth returns the width of a single grapheme cluster: the sum of
326 // the widths of its runes, capped at 2 cells. The cap keeps multi-rune
327 // sequences that render as a single glyph (ZWJ emoji, flags, Hangul jamo)
328 // from being counted wider than the two cells terminals give them.
329 func (c *Condition) graphemeWidth(cluster string) int {
330 width := 0
331 for _, r := range cluster {
332 width += c.RuneWidth(r)
333 }
334 if width > 2 {
335 width = 2
336 }
337 return width
338 }
339
340 // StringWidth return width as you can see
341 func (c *Condition) StringWidth(s string) (width int) {
342 if len(s) == 1 {
343 b := s[0]
344 if b < 0x20 || b == 0x7F {
345 return 0
346 }
347 return 1
348 }
349 if len(s) > 0 && len(s) <= utf8.UTFMax {
350 r, size := utf8.DecodeRuneInString(s)
351 if size == len(s) {
352 return c.RuneWidth(r)
353 }
354 }
355 // ASCII fast path: no grapheme clustering needed for pure ASCII
356 for i := 0; i < len(s); i++ {
357 b := s[i]
358 if b >= 0x80 {
359 goto graphemes
360 }
361 if b >= 0x20 && b != 0x7F {
362 width++
363 }
364 }
365 return
366
367 graphemes:
368 width = 0
369 g := graphemes.FromString(s)
370 for g.Next() {
371 width += c.graphemeWidth(g.Value())
372 }
373 return
374 }
375
376 // Truncate return string truncated with w cells
377 func (c *Condition) Truncate(s string, w int, tail string) string {
378 if c.StringWidth(s) <= w {
379 return s
380 }
381 w -= c.StringWidth(tail)
382 var width int
383 pos := len(s)
384 g := graphemes.FromString(s)
385 for g.Next() {
386 chWidth := c.graphemeWidth(g.Value())
387 if width+chWidth > w {
388 pos = g.Start()
389 break
390 }
391 width += chWidth
392 }
393 return s[:pos] + tail
394 }
395
396 // TruncateLeft cuts w cells from the beginning of the `s`.
397 func (c *Condition) TruncateLeft(s string, w int, prefix string) string {
398 if c.StringWidth(s) <= w {
399 return prefix
400 }
401
402 var width int
403 pos := len(s)
404
405 g := graphemes.FromString(s)
406 for g.Next() {
407 chWidth := c.graphemeWidth(g.Value())
408
409 if width+chWidth > w {
410 if width < w {
411 pos = g.End()
412 prefix += strings.Repeat(" ", width+chWidth-w)
413 } else {
414 pos = g.Start()
415 }
416
417 break
418 }
419
420 width += chWidth
421 }
422
423 return prefix + s[pos:]
424 }
425
426 // TruncatePrefix cuts the beginning of `s` so the result fits in w cells, with prefix prepended
427 func (c *Condition) TruncatePrefix(s string, w int, prefix string) string {
428 if c.StringWidth(prefix) >= w {
429 return prefix
430 }
431
432 sw := c.StringWidth(s)
433 if sw <= w {
434 return s
435 }
436 w -= c.StringWidth(prefix)
437 var width int
438 var pos int
439 g := graphemes.FromString(s)
440 for g.Next() {
441 chWidth := c.graphemeWidth(g.Value())
442 if sw-(width+chWidth) <= w {
443 pos = g.End()
444 break
445 }
446 width += chWidth
447 }
448
449 return prefix + s[pos:]
450 }
451
452 // Wrap return string wrapped with w cells
453 func (c *Condition) Wrap(s string, w int) string {
454 width := 0
455 var out strings.Builder
456 out.Grow(len(s) + len(s)/w + 1)
457 for _, r := range s {
458 cw := c.RuneWidth(r)
459 if r == '\n' {
460 out.WriteRune(r)
461 width = 0
462 continue
463 } else if width+cw > w {
464 out.WriteByte('\n')
465 width = 0
466 out.WriteRune(r)
467 width += cw
468 continue
469 }
470 out.WriteRune(r)
471 width += cw
472 }
473 return out.String()
474 }
475
476 // FillLeft return string filled in left by spaces in w cells
477 func (c *Condition) FillLeft(s string, w int) string {
478 width := c.StringWidth(s)
479 count := w - width
480 if count > 0 {
481 return strings.Repeat(" ", count) + s
482 }
483 return s
484 }
485
486 // FillRight return string filled in left by spaces in w cells
487 func (c *Condition) FillRight(s string, w int) string {
488 width := c.StringWidth(s)
489 count := w - width
490 if count > 0 {
491 return s + strings.Repeat(" ", count)
492 }
493 return s
494 }
495
496 // RuneWidth returns the number of cells in r.
497 // See http://www.unicode.org/reports/tr11/
498 func RuneWidth(r rune) int {
499 return DefaultCondition.RuneWidth(r)
500 }
501
502 // IsAmbiguousWidth returns whether is ambiguous width or not.
503 func IsAmbiguousWidth(r rune) bool {
504 return inTable(r, private) || inTable(r, ambiguous)
505 }
506
507 // IsCombiningWidth returns whether is combining width or not.
508 func IsCombiningWidth(r rune) bool {
509 return inTable(r, combining)
510 }
511
512 // IsNeutralWidth returns whether is neutral width or not.
513 func IsNeutralWidth(r rune) bool {
514 return inTable(r, neutral)
515 }
516
517 // StringWidth return width as you can see
518 func StringWidth(s string) (width int) {
519 return DefaultCondition.StringWidth(s)
520 }
521
522 // Truncate return string truncated with w cells
523 func Truncate(s string, w int, tail string) string {
524 return DefaultCondition.Truncate(s, w, tail)
525 }
526
527 // TruncateLeft cuts w cells from the beginning of the `s`.
528 func TruncateLeft(s string, w int, prefix string) string {
529 return DefaultCondition.TruncateLeft(s, w, prefix)
530 }
531
532 // TruncatePrefix cuts the beginning of `s` so the result fits in w cells, with prefix prepended
533 func TruncatePrefix(s string, w int, prefix string) string {
534 return DefaultCondition.TruncatePrefix(s, w, prefix)
535 }
536
537 // Wrap return string wrapped with w cells
538 func Wrap(s string, w int) string {
539 return DefaultCondition.Wrap(s, w)
540 }
541
542 // FillLeft return string filled in left by spaces in w cells
543 func FillLeft(s string, w int) string {
544 return DefaultCondition.FillLeft(s, w)
545 }
546
547 // FillRight return string filled in left by spaces in w cells
548 func FillRight(s string, w int) string {
549 return DefaultCondition.FillRight(s, w)
550 }
551
552 // CreateLUT will create an in-memory lookup table of 557055 bytes for faster operation.
553 // This should not be called concurrently with other operations.
554 func CreateLUT() {
555 if len(DefaultCondition.combinedLut) > 0 {
556 return
557 }
558 DefaultCondition.CreateLUT()
559 }