Module: CLI::UI::ANSI

Extended by:
T::Sig
Defined in:
lib/cli/ui/ansi.rb

Constant Summary collapse

ESC =
"\x1b"

Class Method Summary collapse

Methods included from T::Sig

sig

Class Method Details

.clear_to_end_of_lineObject


175
176
177
# File 'lib/cli/ui/ansi.rb', line 175

def self.clear_to_end_of_line
  control('', 'K')
end

.control(args, cmd) ⇒ Object


55
56
57
# File 'lib/cli/ui/ansi.rb', line 55

def self.control(args, cmd)
  ESC + '[' + args + cmd
end

.cursor_back(n = 1) ⇒ Object


113
114
115
116
117
# File 'lib/cli/ui/ansi.rb', line 113

def self.cursor_back(n = 1)
  return '' if n.zero?

  control(n.to_s, 'D')
end

.cursor_down(n = 1) ⇒ Object


87
88
89
90
91
# File 'lib/cli/ui/ansi.rb', line 87

def self.cursor_down(n = 1)
  return '' if n.zero?

  control(n.to_s, 'B')
end

.cursor_forward(n = 1) ⇒ Object


100
101
102
103
104
# File 'lib/cli/ui/ansi.rb', line 100

def self.cursor_forward(n = 1)
  return '' if n.zero?

  control(n.to_s, 'C')
end

.cursor_horizontal_absolute(n = 1) ⇒ Object


126
127
128
129
130
# File 'lib/cli/ui/ansi.rb', line 126

def self.cursor_horizontal_absolute(n = 1)
  cmd = control(n.to_s, 'G')
  cmd += cursor_back if CLI::UI::OS.current.shift_cursor_back_on_horizontal_absolute?
  cmd
end

.cursor_restoreObject


156
157
158
# File 'lib/cli/ui/ansi.rb', line 156

def self.cursor_restore
  control('', 'u')
end

.cursor_saveObject


149
150
151
# File 'lib/cli/ui/ansi.rb', line 149

def self.cursor_save
  control('', 's')
end

.cursor_up(n = 1) ⇒ Object


74
75
76
77
78
# File 'lib/cli/ui/ansi.rb', line 74

def self.cursor_up(n = 1)
  return '' if n.zero?

  control(n.to_s, 'A')
end

.hide_cursorObject


142
143
144
# File 'lib/cli/ui/ansi.rb', line 142

def self.hide_cursor
  control('', '?25l')
end

.next_lineObject


163
164
165
# File 'lib/cli/ui/ansi.rb', line 163

def self.next_line
  cursor_down + cursor_horizontal_absolute
end

.previous_lineObject


170
171
172
# File 'lib/cli/ui/ansi.rb', line 170

def self.previous_line
  cursor_up + cursor_horizontal_absolute
end

.printing_width(str) ⇒ Object


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/cli/ui/ansi.rb', line 17

def self.printing_width(str)
  zwj = T.let(false, T::Boolean)
  strip_codes(str).codepoints.reduce(0) do |acc, cp|
    if zwj
      zwj = false
      next acc
    end
    case cp
    when 0x200d # zero-width joiner
      zwj = true
      acc
    when "\n"
      acc
    else
      acc + 1
    end
  end
end

.sgr(params) ⇒ Object


61
62
63
# File 'lib/cli/ui/ansi.rb', line 61

def self.sgr(params)
  control(params, 'm')
end

.show_cursorObject


135
136
137
# File 'lib/cli/ui/ansi.rb', line 135

def self.show_cursor
  control('', '?25h')
end

.strip_codes(str) ⇒ Object


43
44
45
# File 'lib/cli/ui/ansi.rb', line 43

def self.strip_codes(str)
  str.gsub(/\x1b\[[\d;]+[A-z]|\r/, '')
end