about summary refs log tree commit diff stats
path: root/src/utils/strwidth.nim
blob: 4ce9aa127ac8ba71ba4163bc389947d8f50d5de9 (plain) (blame)
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
83
84
85
86
import utils/map
import utils/proptable
import utils/twtuni

include res/map/charwidth_gen

# One of the few global variables in the code. Honestly, it should not exist.
var isCJKAmbiguous* = false

# Warning: this shouldn't be called without normalization.
func width*(u: uint32): int =
  if u <= 0xFFFF: # fast path for BMP
    if u in CombiningTable:
      return 0
    if u in DoubleWidthTable:
      return 2
    {.cast(noSideEffect).}:
      if isCJKAmbiguous and DoubleWidthAmbiguousRanges.isInRange(u):
        return 2
  else:
    if Combining.isInRange(u):
      return 0
    if DoubleWidthRanges.isInRange(u):
      return 2
    {.cast(noSideEffect).}:
      if isCJKAmbiguous and DoubleWidthAmbiguousRanges.isInRange(u):
        return 2
  return 1

# Width, but also works with tabs.
# Needs the column width of the text so far.
func twidth*(u: uint32; w: int): int =
  if u != uint32('\t'):
    return u.width()
  return ((w div 8) + 1) * 8 - w

func width*(s: openArray[char]): int =
  var w = 0
  for u in s.points:
    w += u.twidth(w)
  return w

func width*(s: string; start, len: int): int =
  var w = 0
  var i = start
  var m = len
  if m > s.len:
    m = s.len
  while i < m:
    let u = s.nextUTF8(i)
    w += u.twidth(w)
  return w

func notwidth*(s: openArray[char]): int =
  var w = 0
  for u in s.points:
    w += u.width()
  return w

func twidth*(s: string; w: int): int =
  var i = w
  for u in s.points:
    i += u.twidth(w)
  return i - w

func padToWidth*(s: string; size: int; schar = '$'): string =
  result = newStringOfCap(s.len)
  var w = 0
  var i = 0
  var pi = 0
  while i < s.len:
    pi = i
    w += s.nextUTF8(i).width()
    if w > size - 1:
      break
    for j in pi ..< i:
      result &= s[j]
  if w > size - 1:
    if w == size and i == s.len:
      for j in pi ..< i:
        result &= s[j]
    else:
      result &= schar
  while w < size:
    result &= ' '
    inc w