module Kramdown::Utils::Html

Provides convenience methods for HTML related tasks.

Note that this module has to be mixed into a class that has a @root (containing an element of type :root) and an @options (containing an options hash) instance variable so that some of the methods can work correctly.

Constants

REDUNDANT_LINE_BREAK_REGEX

Public Instance Methods

entity_to_str(e, original = nil) click to toggle source

Convert the entity e to a string. The optional parameter original may contain the original representation of the entity.

This method uses the option entity_output to determine the output form for the entity.

# File lib/kramdown/utils/html.rb, line 26
def entity_to_str(e, original = nil)
  entity_output = @options[:entity_output]

  if entity_output == :as_char &&
      (c = e.char.encode(@root.options[:encoding]) rescue nil) &&
      ((c = e.char) == '"' || !ESCAPE_MAP.key?(c))
    c
  elsif (entity_output == :as_input || entity_output == :as_char) && original
    original
  elsif (entity_output == :symbolic || ESCAPE_MAP.key?(e.char)) && !e.name.nil?
    "&#{e.name};"
  else # default to :numeric
    "&##{e.code_point};"
  end
end
escape_html(str, type = :all) click to toggle source

Escape the special HTML characters in the string str. The parameter type specifies what is escaped: :all - all special HTML characters except the quotation mark as well as entities, :text - all special HTML characters except the quotation mark but no entities and :attribute - all special HTML characters including the quotation mark but no entities.

# File lib/kramdown/utils/html.rb, line 68
def escape_html(str, type = :all)
  str.gsub(ESCAPE_RE_FROM_TYPE[type]) {|m| ESCAPE_MAP[m] || m }
end
fix_cjk_line_break(str) click to toggle source
# File lib/kramdown/utils/html.rb, line 73
def fix_cjk_line_break(str)
  while str.gsub!(REDUNDANT_LINE_BREAK_REGEX, '\1\2')
  end
  str
end
html_attributes(attr) click to toggle source

Return the HTML representation of the attributes attr.

# File lib/kramdown/utils/html.rb, line 43
def html_attributes(attr)
  return '' if attr.empty?

  attr.map do |k, v|
    v.nil? || (k == 'id' && v.strip.empty?) ? '' : " #{k}=\"#{escape_html(v.to_s, :attribute)}\""
  end.join
end