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



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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/ansispan.rb', line 20

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

  # Text styles
  @styles.keys.each do |ansi|
    puts "\[1;#{ansi}m/"
    span = '<span style="font-weight: bold;' + @styles[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