class Kramdown::Converter::Html
Converts a Kramdown::Document to HTML.
You can customize the HTML converter by sub-classing it and overriding the convert_NAME methods. Each such method takes the following parameters:
el-
The element of type
NAMEto be converted. indent-
A number representing the current amount of spaces for indent (only used for block-level elements).
The return value of such a method has to be a string containing the element el formatted as HTML element.
Constants
- FOOTNOTE_BACKLINK_FMT
- ZERO_TO_ONETWENTYEIGHT
Attributes
The amount of indentation used when nesting HTML tags.
Public Class Methods
Initialize the HTML converter with the given Kramdown document doc.
Kramdown::Converter::Base::new
# File lib/kramdown/converter/html.rb 38 def initialize(root, options) 39 super 40 @footnote_counter = @footnote_start = @options[:footnote_nr] 41 @footnotes = [] 42 @footnotes_by_name = {} 43 @footnote_location = nil 44 @toc = [] 45 @toc_code = nil 46 @indent = 2 47 @stack = [] 48 49 # stash string representation of symbol to avoid allocations from multiple interpolations. 50 @highlighter_class = " highlighter-#{options[:syntax_highlighter]}" 51 @dispatcher = Hash.new {|h, k| h[k] = :"convert_#{k}" } 52 end
Public Instance Methods
Add the syntax highlighter name to the ‘class’ attribute of the given attribute hash. And overwrites or add a “language-LANG” part using the lang parameter if lang is not nil.
# File lib/kramdown/converter/html.rb 423 def add_syntax_highlighter_to_class_attr(attr, lang = nil) 424 (attr['class'] = (attr['class'] || '') + @highlighter_class).lstrip! 425 attr['class'].sub!(/\blanguage-\S+|(^)/) { "language-#{lang}#{$1 ? ' ' : ''}" } if lang 426 end
Dispatch the conversion of the element el to a convert_TYPE method using the type of the element.
# File lib/kramdown/converter/html.rb 56 def convert(el, indent = -@indent) 57 send(@dispatcher[el.type], el, indent) 58 end
# File lib/kramdown/converter/html.rb 289 def convert_a(el, indent) 290 format_as_span_html("a", el.attr, inner(el, indent)) 291 end
# File lib/kramdown/converter/html.rb 383 def convert_abbreviation(el, _indent) 384 title = @root.options[:abbrev_defs][el.value] 385 attr = @root.options[:abbrev_attr][el.value].dup 386 attr['title'] = title unless title.empty? 387 format_as_span_html("abbr", attr, el.value) 388 end
# File lib/kramdown/converter/html.rb 76 def convert_blank(_el, _indent) 77 "\n" 78 end
# File lib/kramdown/converter/html.rb 144 def convert_blockquote(el, indent) 145 format_as_indented_block_html("blockquote", el.attr, inner(el, indent), indent) 146 end
# File lib/kramdown/converter/html.rb 285 def convert_br(_el, _indent) 286 "<br />" 287 end
# File lib/kramdown/converter/html.rb 114 def convert_codeblock(el, indent) 115 attr = el.attr.dup 116 lang = extract_code_language!(attr) 117 hl_opts = {} 118 highlighted_code = highlight_code(el.value, el.options[:lang] || lang, :block, hl_opts) 119 120 if highlighted_code 121 add_syntax_highlighter_to_class_attr(attr, lang || hl_opts[:default_lang]) 122 "#{' ' * indent}<div#{html_attributes(attr)}>#{highlighted_code}#{' ' * indent}</div>\n" 123 else 124 result = escape_html(el.value) 125 result.chomp! 126 if el.attr['class'].to_s =~ /\bshow-whitespaces\b/ 127 result.gsub!(/(?:(^[ \t]+)|([ \t]+$)|([ \t]+))/) do |m| 128 suffix = ($1 ? '-l' : ($2 ? '-r' : '')) 129 m.scan(/./).map do |c| 130 case c 131 when "\t" then "<span class=\"ws-tab#{suffix}\">\t</span>" 132 when " " then "<span class=\"ws-space#{suffix}\">⋅</span>" 133 end 134 end.join 135 end 136 end 137 code_attr = {} 138 code_attr['class'] = "language-#{lang}" if lang 139 "#{' ' * indent}<pre#{html_attributes(attr)}>" \ 140 "<code#{html_attributes(code_attr)}>#{result}\n</code></pre>\n" 141 end 142 end
# File lib/kramdown/converter/html.rb 297 def convert_codespan(el, _indent) 298 attr = el.attr.dup 299 lang = extract_code_language(attr) 300 hl_opts = {} 301 result = highlight_code(el.value, lang, :span, hl_opts) 302 if result 303 add_syntax_highlighter_to_class_attr(attr, lang || hl_opts[:default_lang]) 304 else 305 result = escape_html(el.value) 306 end 307 308 format_as_span_html('code', attr, result) 309 end
# File lib/kramdown/converter/html.rb 277 def convert_comment(el, indent) 278 if el.options[:category] == :block 279 "#{' ' * indent}<!-- #{el.value} -->\n" 280 else 281 "<!-- #{el.value} -->" 282 end 283 end
# File lib/kramdown/converter/html.rb 191 def convert_dl(el, indent) 192 format_as_indented_block_html("dl", el.attr, inner(el, indent), indent) 193 end
# File lib/kramdown/converter/html.rb 207 def convert_dt(el, indent) 208 attr = el.attr.dup 209 @stack.last.options[:ial][:refs].each do |ref| 210 if ref =~ /\Aauto_ids(?:-([\w-]+))?/ 211 attr['id'] = "#{$1}#{basic_generate_id(el.options[:raw_text])}".lstrip 212 break 213 end 214 end if !attr['id'] && @stack.last.options[:ial] && @stack.last.options[:ial][:refs] 215 format_as_block_html("dt", attr, inner(el, indent), indent) 216 end
# File lib/kramdown/converter/html.rb 337 def convert_em(el, indent) 338 format_as_span_html(el.type, el.attr, inner(el, indent)) 339 end
# File lib/kramdown/converter/html.rb 342 def convert_entity(el, _indent) 343 entity_to_str(el.value, el.options[:original]) 344 end
# File lib/kramdown/converter/html.rb 311 def convert_footnote(el, _indent) 312 repeat = '' 313 name = @options[:footnote_prefix] + el.options[:name] 314 if (footnote = @footnotes_by_name[name]) 315 number = footnote[2] 316 repeat = ":#{footnote[3] += 1}" 317 else 318 number = @footnote_counter 319 @footnote_counter += 1 320 @footnotes << [name, el.value, number, 0] 321 @footnotes_by_name[name] = @footnotes.last 322 end 323 formatted_link_text = sprintf(@options[:footnote_link_text], number) 324 "<sup id=\"fnref:#{name}#{repeat}\">" \ 325 "<a href=\"#fn:#{name}\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">" \ 326 "#{formatted_link_text}</a></sup>" 327 end
# File lib/kramdown/converter/html.rb 148 def convert_header(el, indent) 149 attr = el.attr.dup 150 if @options[:auto_ids] && !attr['id'] 151 attr['id'] = generate_id(el.options[:raw_text]) 152 end 153 154 if @options[:header_links] && attr['id'].to_s.length > 0 155 link = Element.new(:a, nil, nil) 156 link.attr['href'] = "##{attr['id']}" 157 unless (header_link_text = @options[:header_links][:content].to_s).empty? 158 link.children << Element.new(:text, header_link_text) 159 end 160 if @options[:header_links][:position].to_s == 'start' 161 el.children.unshift(link) 162 else 163 el.children.push(link) 164 end 165 end 166 167 @toc << [el.options[:level], attr['id'], el.children] if attr['id'] && in_toc?(el) 168 level = output_header_level(el.options[:level]) 169 format_as_block_html("h#{level}", attr, inner(el, indent), indent) 170 end
# File lib/kramdown/converter/html.rb 172 def convert_hr(el, indent) 173 "#{' ' * indent}<hr#{html_attributes(el.attr)} />\n" 174 end
# File lib/kramdown/converter/html.rb 218 def convert_html_element(el, indent) 219 res = inner(el, indent) 220 if el.options[:category] == :span 221 "<#{el.value}#{html_attributes(el.attr)}" + \ 222 (res.empty? && HTML_ELEMENTS_WITHOUT_BODY.include?(el.value) ? " />" : ">#{res}</#{el.value}>") 223 else 224 output = +'' 225 if @stack.last.type != :html_element || @stack.last.options[:content_model] != :raw 226 output << ' ' * indent 227 end 228 output << "<#{el.value}#{html_attributes(el.attr)}" 229 if el.options[:is_closed] && el.options[:content_model] == :raw 230 output << " />" 231 elsif !res.empty? && el.options[:content_model] != :block 232 output << ">#{res}</#{el.value}>" 233 elsif !res.empty? 234 output << ">\n#{res.chomp}\n" << ' ' * indent << "</#{el.value}>" 235 elsif HTML_ELEMENTS_WITHOUT_BODY.include?(el.value) 236 output << " />" 237 else 238 output << "></#{el.value}>" 239 end 240 output << "\n" if @stack.last.type != :html_element || @stack.last.options[:content_model] != :raw 241 output 242 end 243 end
# File lib/kramdown/converter/html.rb 293 def convert_img(el, _indent) 294 "<img#{html_attributes(el.attr)} />" 295 end
# File lib/kramdown/converter/html.rb 195 def convert_li(el, indent) 196 output = ' ' * indent << "<#{el.type}" << html_attributes(el.attr) << ">" 197 res = inner(el, indent) 198 if el.children.empty? || (el.children.first.type == :p && el.children.first.options[:transparent]) 199 output << res << (res.match?(/\n\Z/) ? ' ' * indent : '') 200 else 201 output << "\n" << res << ' ' * indent 202 end 203 output << "</#{el.type}>\n" 204 end
# File lib/kramdown/converter/html.rb 369 def convert_math(el, indent) 370 if (result = format_math(el, indent: indent)) 371 result 372 else 373 attr = el.attr.dup 374 attr['class'] = "#{attr['class']} kdmath".lstrip 375 if el.options[:category] == :block 376 format_as_block_html('div', attr, "$$\n#{el.value}\n$$", indent) 377 else 378 format_as_span_html('span', attr, "$#{el.value}$") 379 end 380 end 381 end
# File lib/kramdown/converter/html.rb 85 def convert_p(el, indent) 86 if el.options[:transparent] 87 inner(el, indent) 88 elsif el.children.size == 1 && el.children.first.type == :img && 89 el.children.first.options[:ial]&.[](:refs)&.include?('standalone') 90 convert_standalone_image(el, indent) 91 else 92 format_as_block_html("p", el.attr, inner(el, indent), indent) 93 end 94 end
# File lib/kramdown/converter/html.rb 329 def convert_raw(el, _indent) 330 if !el.options[:type] || el.options[:type].empty? || el.options[:type].include?('html') 331 el.value + (el.options[:category] == :block ? "\n" : '') 332 else 333 '' 334 end 335 end
# File lib/kramdown/converter/html.rb 390 def convert_root(el, indent) 391 result = inner(el, indent) 392 if @footnote_location 393 result.sub!(/#{@footnote_location}/, footnote_content.gsub(/\\/, "\\\\\\\\")) 394 else 395 result << footnote_content 396 end 397 if @toc_code 398 toc_tree = generate_toc_tree(@toc, @toc_code[0], @toc_code[1] || {}) 399 text = toc_tree.children.empty? ? '' : convert(toc_tree, 0) 400 result.sub!(/#{@toc_code.last}/, text.gsub(/\\/, "\\\\\\\\")) 401 end 402 result 403 end
# File lib/kramdown/converter/html.rb 365 def convert_smart_quote(el, _indent) 366 entity_to_str(smart_quote_entity(el)) 367 end
Helper method used by convert_p to convert a paragraph that only contains a single :img element.
# File lib/kramdown/converter/html.rb 98 def convert_standalone_image(el, indent) 99 figure_attr = el.attr.dup 100 image_attr = el.children.first.attr.dup 101 102 if image_attr.key?('class') && !figure_attr.key?('class') 103 figure_attr['class'] = image_attr.delete('class') 104 end 105 if image_attr.key?('id') && !figure_attr.key?('id') 106 figure_attr['id'] = image_attr.delete('id') 107 end 108 109 body = "#{' ' * (indent + @indent)}<img#{html_attributes(image_attr)} />\n" \ 110 "#{' ' * (indent + @indent)}<figcaption>#{image_attr['alt']}</figcaption>\n" 111 format_as_indented_block_html("figure", figure_attr, body, indent) 112 end
# File lib/kramdown/converter/html.rb 255 def convert_table(el, indent) 256 format_as_indented_block_html(el.type, el.attr, inner(el, indent), indent) 257 end
# File lib/kramdown/converter/html.rb 265 def convert_td(el, indent) 266 res = inner(el, indent) 267 type = (@stack[-2].type == :thead ? :th : :td) 268 attr = el.attr 269 alignment = @stack[-3].options[:alignment][@stack.last.children.index(el)] 270 if alignment != :default 271 attr = el.attr.dup 272 attr['style'] = (attr.key?('style') ? "#{attr['style']}; " : '') + "text-align: #{alignment}" 273 end 274 format_as_block_html(type, attr, res.empty? ? entity_to_str(ENTITY_NBSP) : res, indent) 275 end
# File lib/kramdown/converter/html.rb 80 def convert_text(el, _indent) 81 escaped = escape_html(el.value, :text) 82 @options[:remove_line_breaks_for_cjk] ? fix_cjk_line_break(escaped) : escaped 83 end
# File lib/kramdown/converter/html.rb 357 def convert_typographic_sym(el, _indent) 358 if (result = @options[:typographic_symbols][el.value]) 359 escape_html(result, :text) 360 else 361 TYPOGRAPHIC_SYMS[el.value].map {|e| entity_to_str(e) }.join 362 end 363 end
# File lib/kramdown/converter/html.rb 179 def convert_ul(el, indent) 180 if !@toc_code && el.options.dig(:ial, :refs)&.include?('toc') 181 @toc_code = [el.type, el.attr, ZERO_TO_ONETWENTYEIGHT.map { rand(36).to_s(36) }.join] 182 @toc_code.last 183 elsif !@footnote_location && el.options.dig(:ial, :refs)&.include?('footnotes') 184 @footnote_location = ZERO_TO_ONETWENTYEIGHT.map { rand(36).to_s(36) }.join 185 else 186 format_as_indented_block_html(el.type, el.attr, inner(el, indent), indent) 187 end 188 end
# File lib/kramdown/converter/html.rb 245 def convert_xml_comment(el, indent) 246 if el.options[:category] == :block && 247 (@stack.last.type != :html_element || @stack.last.options[:content_model] != :raw) 248 ' ' * indent << el.value << "\n" 249 else 250 el.value 251 end 252 end
Fixes the elements for use in a TOC entry.
# File lib/kramdown/converter/html.rb 467 def fix_for_toc_entry(elements) 468 remove_footnotes(elements) 469 unwrap_links(elements) 470 elements 471 end
Return an HTML ordered list with the footnote content for the used footnotes.
# File lib/kramdown/converter/html.rb 502 def footnote_content 503 ol = Element.new(:ol) 504 ol.attr['start'] = @footnote_start if @footnote_start != 1 505 i = 0 506 backlink_text = escape_html(@options[:footnote_backlink], :text) 507 while i < @footnotes.length 508 name, data, _, repeat = *@footnotes[i] 509 li = Element.new(:li, nil, 'id' => "fn:#{name}") 510 li.children = Marshal.load(Marshal.dump(data.children)) 511 512 para = nil 513 if li.children.last&.type == :p || @options[:footnote_backlink_inline] 514 parent = li 515 while !parent.children.empty? && ![:p, :header].include?(parent.children.last.type) 516 parent = parent.children.last 517 end 518 para = parent.children.last 519 insert_space = true 520 end 521 522 unless para 523 li.children << (para = Element.new(:p)) 524 insert_space = false 525 end 526 527 unless @options[:footnote_backlink].empty? 528 nbsp = entity_to_str(ENTITY_NBSP) 529 value = sprintf(FOOTNOTE_BACKLINK_FMT, (insert_space ? nbsp : ''), name, backlink_text) 530 para.children << Element.new(:raw, value) 531 (1..repeat).each do |index| 532 value = sprintf(FOOTNOTE_BACKLINK_FMT, nbsp, "#{name}:#{index}", 533 "#{backlink_text}<sup>#{index + 1}</sup>") 534 para.children << Element.new(:raw, value) 535 end 536 end 537 538 ol.children << Element.new(:raw, convert(li, 4)) 539 i += 1 540 end 541 if ol.children.empty? 542 '' 543 else 544 format_as_indented_block_html('div', {class: "footnotes", role: "doc-endnotes"}, convert(ol, 2), 0) 545 end 546 end
Format the given element as block HTML.
# File lib/kramdown/converter/html.rb 411 def format_as_block_html(name, attr, body, indent) 412 "#{' ' * indent}<#{name}#{html_attributes(attr)}>#{body}</#{name}>\n" 413 end
Format the given element as block HTML with a newline after the start tag and indentation before the end tag.
# File lib/kramdown/converter/html.rb 417 def format_as_indented_block_html(name, attr, body, indent) 418 "#{' ' * indent}<#{name}#{html_attributes(attr)}>\n#{body}#{' ' * indent}</#{name}>\n" 419 end
Format the given element as span HTML.
# File lib/kramdown/converter/html.rb 406 def format_as_span_html(name, attr, body) 407 "<#{name}#{html_attributes(attr)}>#{body}</#{name}>" 408 end
Generate and return an element tree for the table of contents.
# File lib/kramdown/converter/html.rb 429 def generate_toc_tree(toc, type, attr) 430 sections = Element.new(type, nil, attr.dup) 431 sections.attr['id'] ||= 'markdown-toc' 432 stack = [] 433 toc.each do |level, id, children| 434 li = Element.new(:li, nil, nil, level: level) 435 li.children << Element.new(:p, nil, nil, transparent: true) 436 a = Element.new(:a, nil) 437 a.attr['href'] = "##{id}" 438 a.attr['id'] = "#{sections.attr['id']}-#{id}" 439 a.children.concat(fix_for_toc_entry(Marshal.load(Marshal.dump(children)))) 440 li.children.last.children << a 441 li.children << Element.new(type) 442 443 success = false 444 until success 445 if stack.empty? 446 sections.children << li 447 stack << li 448 success = true 449 elsif stack.last.options[:level] < li.options[:level] 450 stack.last.children.last.children << li 451 stack << li 452 success = true 453 else 454 item = stack.pop 455 item.children.pop if item.children.last.children.empty? 456 end 457 end 458 end 459 until stack.empty? 460 item = stack.pop 461 item.children.pop if item.children.last.children.empty? 462 end 463 sections 464 end
Return the converted content of the children of el as a string. The parameter indent has to be the amount of indentation used for the element el.
Pushes el onto the @stack before converting the child elements and pops it from the stack afterwards.
# File lib/kramdown/converter/html.rb 65 def inner(el, indent) 66 result = +'' 67 indent += @indent 68 @stack.push(el) 69 el.children.each do |inner_el| 70 result << send(@dispatcher[inner_el.type], inner_el, indent) 71 end 72 @stack.pop 73 result 74 end
Obfuscate the text by using HTML entities.
# File lib/kramdown/converter/html.rb 490 def obfuscate(text) 491 result = +'' 492 text.each_byte do |b| 493 result << (b > 128 ? b.chr : sprintf("&#%03d;", b)) 494 end 495 result.force_encoding(text.encoding) 496 result 497 end
Remove all footnotes from the given elements.
# File lib/kramdown/converter/html.rb 482 def remove_footnotes(elements) 483 elements.delete_if do |c| 484 remove_footnotes(c.children) 485 c.type == :footnote 486 end 487 end
Remove all link elements by unwrapping them.
# File lib/kramdown/converter/html.rb 474 def unwrap_links(elements) 475 elements.map! do |c| 476 unwrap_links(c.children) 477 c.type == :a ? c.children : c 478 end.flatten! 479 end