Module: Keisanjaku::ANSI

Defined in:
lib/keisanjaku/ansi.rb

Constant Summary collapse

CODES =
{
  reset: 0,
  red: 31,
  yellow: 33,
  cyan_bg: 46,
  bold: 1
}.freeze
AMBIGUOUS_WIDE_CHARS =
"×÷±−√°·".chars.freeze

Class Method Summary collapse

Class Method Details

.clear_screenObject



25
26
27
# File 'lib/keisanjaku/ansi.rb', line 25

def clear_screen
  "\e[2J\e[H"
end

.enabled?(color) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/keisanjaku/ansi.rb', line 14

def enabled?(color)
  color && ENV["NO_COLOR"].nil?
end

.fit(text, width) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/keisanjaku/ansi.rb', line 45

def fit(text, width)
  stripped_width = visible_width(text)
  return text + (" " * (width - stripped_width)) if stripped_width < width
  return text if stripped_width == width

  truncate(text, width)
end

.hide_cursorObject



29
30
31
# File 'lib/keisanjaku/ansi.rb', line 29

def hide_cursor
  "\e[?25l"
end

.paint(text, *styles, color: true) ⇒ Object



18
19
20
21
22
23
# File 'lib/keisanjaku/ansi.rb', line 18

def paint(text, *styles, color: true)
  return text unless enabled?(color)

  codes = styles.map { |style| CODES.fetch(style) }.join(";")
  "\e[#{codes}m#{text}\e[0m"
end

.show_cursorObject



33
34
35
# File 'lib/keisanjaku/ansi.rb', line 33

def show_cursor
  "\e[?25h"
end

.strip(text) ⇒ Object



37
38
39
# File 'lib/keisanjaku/ansi.rb', line 37

def strip(text)
  text.gsub(/\e\[[0-9;?]*[A-Za-z]/, "")
end

.truncate(text, width) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/keisanjaku/ansi.rb', line 53

def truncate(text, width)
  output = +""
  used = 0
  strip(text).each_char do |char|
    char_width = wide?(char) ? 2 : 1
    break if used + char_width > width

    output << char
    used += char_width
  end
  output << (" " * (width - used))
end

.visible_width(text) ⇒ Object



41
42
43
# File 'lib/keisanjaku/ansi.rb', line 41

def visible_width(text)
  strip(text).each_char.sum { |char| wide?(char) ? 2 : 1 }
end

.wide?(char) ⇒ Boolean

Returns:

  • (Boolean)


66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/keisanjaku/ansi.rb', line 66

def wide?(char)
  code = char.ord
  (0x1100..0x115F).cover?(code) ||
    (0x2E80..0xA4CF).cover?(code) ||
    (0xAC00..0xD7A3).cover?(code) ||
    (0xF900..0xFAFF).cover?(code) ||
    (0xFE10..0xFE19).cover?(code) ||
  (0xFE30..0xFE6F).cover?(code) ||
    (0xFF00..0xFF60).cover?(code) ||
    (0xFFE0..0xFFE6).cover?(code) ||
    AMBIGUOUS_WIDE_CHARS.include?(char)
end