Module: Railbow::TextUtils

Included in:
Formatters::Base, Railbow::Table::Renderer
Defined in:
lib/railbow/text_utils.rb

Instance Method Summary collapse

Instance Method Details

#display_width(str) ⇒ Object



11
12
13
# File 'lib/railbow/text_utils.rb', line 11

def display_width(str)
  Unicode::DisplayWidth.of(str.to_s)
end

#strip_ansi(str) ⇒ Object



7
8
9
# File 'lib/railbow/text_utils.rb', line 7

def strip_ansi(str)
  str.to_s.gsub(/\e\[[0-9;]*m/, "")
end

#truncate_ansi(str, max_width) ⇒ Object

ANSI-aware counterpart to truncate_str: escape codes pass through unmeasured, and a color left open at the cut is closed before the ellipsis so it cannot leak into whatever follows the cell.



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
# File 'lib/railbow/text_utils.rb', line 33

def truncate_ansi(str, max_width)
  s = str.to_s
  return s if display_width(strip_ansi(s)) <= max_width

  result = +""
  width = 0
  open_color = false
  i = 0
  while i < s.length
    if s[i] == "\e" && (close = s.index("m", i))
      code = s[i..close]
      result << code
      open_color = (code != "\e[0m")
      i = close + 1
    else
      ch = s[i]
      ch_width = display_width(ch)
      break if width + ch_width > max_width - 3
      result << ch
      width += ch_width
      i += 1
    end
  end
  result << "\e[0m" if open_color
  "#{result}..."
end

#truncate_str(str, max_width) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/railbow/text_utils.rb', line 15

def truncate_str(str, max_width)
  return str if display_width(strip_ansi(str)) <= max_width

  plain = strip_ansi(str)
  truncated = +""
  width = 0
  plain.each_char do |ch|
    ch_width = display_width(ch)
    break if width + ch_width > max_width - 3
    truncated << ch
    width += ch_width
  end
  "#{truncated}..."
end