Module: Shellfie::AnsiNormalizer

Defined in:
lib/shellfie/ansi_normalizer.rb

Constant Summary collapse

ANSI_REGEX =
/\e\[([0-9;]*)m/
OSC_REGEX =
/\e\].*?(?:\a|\e\\)/
CSI_CONTROL_REGEX =
/\e\[[0-9;?]*[A-Za-ln-z]/

Class Method Summary collapse

Class Method Details

.apply_line_controls(text) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/shellfie/ansi_normalizer.rb', line 20

def apply_line_controls(text)
  buffer = AnsiLineBuffer.new
  scanner = StringScanner.new(text)

  until scanner.eos?
    if scanner.scan(ANSI_REGEX)
      buffer.write_escape(scanner.matched)
      next
    end

    if scanner.scan(/\e\[([0-9;?]*)[JK]/)
      buffer.clear(scanner.matched[-1], scanner[1])
      next
    end

    if scanner.scan(/\e\[([0-9;?]*)[CDG]/)
      buffer.move(scanner.matched[-1], scanner[1])
      next
    end

    if scanner.scan(/\e\[([0-9;?]*)[Hf]/)
      buffer.position(scanner[1])
      next
    end

    buffer.write_character(scanner.getch)
  end

  buffer.to_s
end

.normalize(text) ⇒ Object



14
15
16
17
18
# File 'lib/shellfie/ansi_normalizer.rb', line 14

def normalize(text)
  text = text.gsub(OSC_REGEX, "")
  text = apply_line_controls(text)
  text.gsub(CSI_CONTROL_REGEX, "")
end