Module: HtmlToAnsi::Html::Conversions

Defined in:
lib/html_to_ansi/html/conversions.rb

Class Method Summary collapse

Class Method Details

.html_to_ansi(text, wrap: true, width: nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/html_to_ansi/html/conversions.rb', line 5

def self.html_to_ansi text, wrap: true, width: nil
  return '' if text.strip == ''
  output = ''
  begin
    doc = Html.parse("<body>#{text.gsub(/\r/, '').strip}</body>")
    output = AnsiFormatter.new.format(doc) + Ansi.graphics_mode(Ansi::Code::Attribute::NORMAL)
    output = Html.decode(output)
  rescue REXML::ParseException => e
    output = text.strip
  end
  calc_width = width || size[0]
  if calc_width.nil? or !wrap
    output
  else
    terminalize(output, calc_width - 1)
  end
end

.html_to_text(text, wrap: true, width: nil) ⇒ Object



23
24
25
26
# File 'lib/html_to_ansi/html/conversions.rb', line 23

def self.html_to_text text, wrap: true, width: nil
  text = html_to_ansi text, wrap: wrap, width: width
  text.gsub(/\e\[([;\d]+)?m/, '').gsub(/\n +\n/, "\n\n")
end

.sizeObject



231
232
233
234
235
# File 'lib/html_to_ansi/html/conversions.rb', line 231

def self.size
  STDOUT.winsize.reverse
rescue
  [nil,nil]
end

.terminalize(string, max_length) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/html_to_ansi/html/conversions.rb', line 199

def self.terminalize string, max_length
  i = 0
  output = ''
  line_length = 0
  while i < string.length
    line_length += 1
    char = string[i,1]
    if char == "\e"
      # Right now, graphics modes are the only supported ANSI sequences.
      end_of_seq = string.index("m", i)
      output += string[i..end_of_seq]
      i = end_of_seq + 1
    elsif char == " "
      next_space = string.index(/[\s]/, i + 1)
      if !next_space.nil? and line_length + (next_space - i) > max_length
        output += "\n"
        line_length = 0
      else
        output += char
      end
      i += 1
    else
      if char == "\n"
        line_length = 0
      end
      output += char
      i += 1
    end
  end
  output
end