Class: Shellfie::AnsiParser

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

Constant Summary collapse

ANSI_REGEX =
/\e\[([0-9;]*)m/

Instance Method Summary collapse

Constructor Details

#initialize(state_mode: :persistent) ⇒ AnsiParser

Returns a new instance of AnsiParser.



25
26
27
28
# File 'lib/shellfie/ansi_parser.rb', line 25

def initialize(state_mode: :persistent)
  @state_mode = state_mode.to_sym
  reset_state
end

Instance Method Details

#parse(text) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/shellfie/ansi_parser.rb', line 30

def parse(text)
  reset_state if @state_mode == :line

  segments = []
  scanner = StringScanner.new(AnsiNormalizer.normalize(text.to_s))
  current_text = +""

  until scanner.eos?
    if scanner.scan(ANSI_REGEX)
      unless current_text.empty?
        segments << create_segment(current_text)
        current_text = +""
      end
      process_codes(scanner[1])
    else
      current_text << scanner.getch
    end
  end

  segments << create_segment(current_text) unless current_text.empty?
  segments
end