Class: Shellfie::AnsiParser

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

Constant Summary collapse

ANSI_REGEX =
/\e\[([0-9;:]*)m/
OSC_REGEX =
/\e\](.*?)?(?:\a|\e\\)/m
2_048
MAX_OSC_BYTES =
MAX_LINK_BYTES + 64
%w[http https mailto].freeze

Instance Method Summary collapse

Constructor Details

#initialize(state_mode: :persistent, tab_width: 8, osc_policy: "ignore", graphics_policy: "ignore") ⇒ AnsiParser

Returns a new instance of AnsiParser.



37
38
39
40
41
42
43
44
45
# File 'lib/shellfie/ansi_parser.rb', line 37

def initialize(state_mode: :persistent, tab_width: 8, osc_policy: "ignore", graphics_policy: "ignore")
  @state_mode = state_mode.to_sym
  @tab_width = tab_width
  @osc_policy = osc_policy.to_s
  @graphics_policy = graphics_policy.to_s
  @link = nil
  @pending_osc = +""
  reset_state
end

Instance Method Details

#parse(text) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/shellfie/ansi_parser.rb', line 47

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

  input = @pending_osc + text.to_s
  reject_terminal_graphics!(input)
  input, @pending_osc = split_incomplete_osc(input)
  segments = []
  scanner = StringScanner.new(AnsiNormalizer.normalize(input, tab_width: @tab_width, osc_policy: @osc_policy))
  current_text = +""

  until scanner.eos?
    if scanner.scan(OSC_REGEX)
      unless current_text.empty?
        segments << create_segment(current_text)
        current_text = +""
      end
      process_osc(scanner[1])
    elsif 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