Class: RubyRich::Markdown::TerminalConverter

Inherits:
Kramdown::Converter::Base
  • Object
show all
Defined in:
lib/ruby_rich/markdown.rb

Overview

将 Markdown 转换为 ANSI 终端输出。使用 kramdown 的 AST 遍历 + 自定义 Converter 实现。

kramdown 比 redcarpet 的优势:

- 纯 Ruby 实现,无需 C 扩展编译
- 原生 GFM 支持(表格、任务列表、删除线)
- 定义列表 (definition lists)
- 脚注 (footnotes)
- 数学公式 (需 math engine)
- 缩写 (abbreviations)
- 活跃维护

Instance Method Summary collapse

Constructor Details

#initialize(root, options) ⇒ TerminalConverter

Returns a new instance of TerminalConverter.



18
19
20
21
22
23
24
25
# File 'lib/ruby_rich/markdown.rb', line 18

def initialize(root, options)
  super
  @width = options[:width] || 80
  @indent_str = options[:indent] || '  '
  @table_border_style = options[:table_border_style] || :simple
  # 用于有序列表编号
  @list_counters = []
end

Instance Method Details

#convert(el, _indent = 0) ⇒ Object

主分发方法 — 根据 AST 元素类型路由到对应处理方法



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
68
69
70
71
72
73
74
# File 'lib/ruby_rich/markdown.rb', line 28

def convert(el, _indent = 0)
  case el.type
  when :root         then convert_children(el)
  when :blank        then "\n"
  when :text         then el.value
  when :p            then convert_p(el)
  when :header       then convert_header(el)
  when :codeblock    then convert_codeblock(el)
  when :codespan     then convert_codespan(el)
  when :blockquote   then convert_blockquote(el)
  when :ul           then convert_list(el)
  when :ol           then convert_list(el)
  when :li           then convert_li(el)
  when :em           then convert_em(el)
  when :strong       then convert_strong(el)
  when :em_strong    then convert_em_strong(el)
  when :a            then convert_link(el)
  when :img          then convert_image(el)
  when :hr           then convert_hr(el)
  when :br           then "\n"
  when :table        then convert_table(el)
  when :thead        then convert_children(el)
  when :tbody        then convert_children(el)
  when :tr           then convert_table_row(el)
  when :th           then convert_table_cell(el)
  when :td           then convert_table_cell(el)
  when :html_element then convert_html_element(el)
  when :html_entity  then convert_html_entity(el)
  when :smart_quote  then convert_smart_quote(el)
  when :entity       then el.value.to_s
  when :raw          then convert_raw(el)
  when :comment      then ''
  when :footnote     then convert_footnote(el)
  when :dl           then convert_definition_list(el)
  when :dt           then convert_definition_term(el)
  when :dd           then convert_definition_desc(el)
  when :abbreviation then convert_abbreviation(el)
  when :math         then convert_math(el)
  else
    # 未知类型,递归处理子元素
    if el.children && !el.children.empty?
      convert_children(el)
    else
      el.value || el.text || ''
    end
  end
end