Class: Shellfie::AnsiLineBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/shellfie/ansi_line_buffer.rb

Constant Summary collapse

CONTINUATION =
Object.new.freeze

Instance Method Summary collapse

Constructor Details

#initialize(tab_width: 8) ⇒ AnsiLineBuffer

Returns a new instance of AnsiLineBuffer.



9
10
11
12
13
14
# File 'lib/shellfie/ansi_line_buffer.rb', line 9

def initialize(tab_width: 8)
  @cells = []
  @column = 0
  @pending_escape = +""
  @tab_width = tab_width
end

Instance Method Details

#clear(command, params) ⇒ Object



60
61
62
63
# File 'lib/shellfie/ansi_line_buffer.rb', line 60

def clear(command, params)
  mode = first_param(params, default: 0)
  command == "K" ? clear_line(mode) : clear_screen(mode)
end

#move(command, params) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/shellfie/ansi_line_buffer.rb', line 42

def move(command, params)
  amount = first_param(params, default: 1)
  case command
  when "C"
    @column += amount
  when "D"
    @column = [@column - amount, 0].max
  when "G"
    @column = [amount - 1, 0].max
  end
end

#position(params) ⇒ Object



54
55
56
57
58
# File 'lib/shellfie/ansi_line_buffer.rb', line 54

def position(params)
  values = params.to_s.split(";")
  column = values.length >= 2 ? Integer(values[1], exception: false) : 1
  @column = [[column || 1, 1].max - 1, 0].max
end

#to_sObject



65
66
67
68
69
70
# File 'lib/shellfie/ansi_line_buffer.rb', line 65

def to_s
  last = @cells.rindex { |cell| !cell.nil? }
  return @pending_escape unless last

  @cells[0..last].map { |cell| cell.equal?(CONTINUATION) ? "" : (cell || " ") }.join + @pending_escape
end

#write_character(char) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/shellfie/ansi_line_buffer.rb', line 20

def write_character(char)
  case char
  when "\r"
    @column = 0
  when "\b"
    @column = [@column - 1, 0].max
  when "\t"
    @column += @tab_width - (@column % @tab_width)
  when "\a"
    nil
  else
    width = TextMetrics.grapheme_width(char)
    return if width.zero?

    clear_wide_cell(@column)
    @cells[@column] = "#{@pending_escape}#{char}"
    @cells[@column + 1] = CONTINUATION if width == 2
    @pending_escape = +""
    @column += width
  end
end

#write_escape(sequence) ⇒ Object



16
17
18
# File 'lib/shellfie/ansi_line_buffer.rb', line 16

def write_escape(sequence)
  @pending_escape << sequence
end