module HtmlToAnsi::Html::Conversions

Public Class Methods

html_to_ansi(text, wrap: true, width: nil) click to toggle source
# 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) click to toggle source
# 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
size() click to toggle source
# File lib/html_to_ansi/html/conversions.rb, line 231
def self.size
  STDOUT.winsize.reverse
rescue
  [nil,nil]
end
terminalize(string, max_length) click to toggle source
# 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