Class: Ansispan

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

Class Method Summary collapse

Class Method Details

.convert(str, escape_character: '\033') ⇒ Object



13
14
15
16
17
18
19
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
50
51
52
53
# File 'lib/ansispan.rb', line 13

def self.convert(str, escape_character: '\033')
  escape_character = Regexp.escape(escape_character)

  @foreground_colors.keys.each do |ansi|
    span = '<span style="color: ' + @foreground_colors[ansi] + '">'
    #
    # `\033[Xm` == `\033[0;Xm` sets foreground color to `X`.
    #

    str = str.gsub(/#{escape_character}\[#{ansi}m/, span)
      .gsub(/#{escape_character}\[#{ansi}m/, span)
  end

  #
  # `\033[1m` enables bold font, `\033[22m` disables it
  #
  str = str.gsub(/#{escape_character}\[1m/, '<b>')
    .gsub(/#{escape_character}\[22m/, '</b>')


  # Bold colors
  @foreground_colors.keys.each do |ansi|
    span = '<span style="font-weight: bold; color: ' + @foreground_colors[ansi] + '">'
    str = str.gsub(/#{escape_character}\[1;#{ansi}m/, span)
  end

  # Underline colors
  @foreground_colors.keys.each do |ansi|
    span = '<span style="text-decoration: underline; color: ' + @foreground_colors[ansi] + '">'
    str = str.gsub(/#{escape_character}\[4;#{ansi}m/, span)
  end
  #
  # `\033[3m` enables italics font, `\033[23m` disables it
  #
  str = str.gsub(/#{escape_character}\[3m/, '<i>')
    .gsub(/#{escape_character}\[23m/, '</i>')

  str = str.gsub(/#{escape_character}\[m/, '</span>');
  str = str.gsub(/#{escape_character}\[0m/, '</span>');
  return str.gsub(/#{escape_character}\[39m/, '</span>');
end