Module: Shellfie::AnsiNormalizer

Defined in:
lib/shellfie/ansi_normalizer.rb

Constant Summary collapse

ANSI_REGEX =
/\e\[([0-9;:]*)m/
OSC_REGEX =
/\e\].*?(?:\a|\e\\)/
STRING_CONTROL_REGEX =
/\e(?:P|_|\^).*?(?:\a|\e\\)/m
INCOMPLETE_STRING_CONTROL_REGEX =
/\e(?:P|_|\^).*\z/m
GRAPHICS_CONTROL_PREFIX =
/\e(?:_G|P[0-9;?]*q|\]1337;File=)/
CSI_CONTROL_REGEX =
/\e\[[0-9;:?]*[A-Za-ln-z]/

Class Method Summary collapse

Class Method Details

.apply_line_controls(text, tab_width: 8) ⇒ Object



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
50
51
52
53
54
55
56
57
58
59
# File 'lib/shellfie/ansi_normalizer.rb', line 25

def apply_line_controls(text, tab_width: 8)
  buffer = AnsiLineBuffer.new(tab_width: tab_width)
  scanner = StringScanner.new(text)

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

    if scanner.scan(OSC_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.scan(/\X/))
  end

  buffer.to_s
end

.normalize(text, tab_width: 8, osc_policy: "ignore") ⇒ Object



17
18
19
20
21
22
23
# File 'lib/shellfie/ansi_normalizer.rb', line 17

def normalize(text, tab_width: 8, osc_policy: "ignore")
  text = text.gsub(STRING_CONTROL_REGEX, "").gsub(INCOMPLETE_STRING_CONTROL_REGEX, "")
  text = TextMetrics.graphemes(text).join
  text = text.gsub(OSC_REGEX) { |sequence| osc_policy == "ignore" || !sequence.start_with?("\e]8;") ? "" : sequence }
  text = apply_line_controls(text, tab_width: tab_width)
  text.gsub(CSI_CONTROL_REGEX, "")
end