Module: Rixie::CLI::Markdown

Defined in:
lib/rixie/cli/markdown.rb

Constant Summary collapse

HEADING_RE =
/\A(\#{1,6})\s+(.+)\z/
BULLET_RE =
/\A(\s*)[-*]\s+(.+)\z/
NUMBERED_RE =
/\A(\s*)(\d+)\.\s+(.+)\z/
BOLD_RE =
/\*\*([^*\n]+)\*\*/
ITALIC_RE =
/(?<!\*)\*([^*\n]+)\*(?!\*)/

Class Method Summary collapse

Class Method Details

.render(text, terminal:) ⇒ Object



14
15
16
# File 'lib/rixie/cli/markdown.rb', line 14

def render(text, terminal:)
  text.split("\n", -1).map { |line| render_line(line, terminal:) }.join("\n")
end

.render_heading(rendered, raw:, level:, terminal:) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/rixie/cli/markdown.rb', line 39

def render_heading(rendered, raw:, level:, terminal:)
  styled = terminal.bold(terminal.accent(rendered))
  case level
  when 1 then "#{styled}\n#{terminal.accent("" * visual_width(raw))}"
  when 2 then "#{styled}\n#{terminal.accent("" * visual_width(raw))}"
  else styled
  end
end

.render_inline(text, terminal:) ⇒ Object



48
49
50
51
52
# File 'lib/rixie/cli/markdown.rb', line 48

def render_inline(text, terminal:)
  text
    .gsub(BOLD_RE) { terminal.bold(::Regexp.last_match(1)) }
    .gsub(ITALIC_RE) { terminal.italic(::Regexp.last_match(1)) }
end

.render_line(line, terminal:) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rixie/cli/markdown.rb', line 18

def render_line(line, terminal:)
  case line
  when HEADING_RE
    level = ::Regexp.last_match(1).length
    raw = ::Regexp.last_match(2)
    rendered = render_inline(raw, terminal:)
    render_heading(rendered, raw: raw, level: level, terminal: terminal)
  when BULLET_RE
    indent = ::Regexp.last_match(1)
    content = render_inline(::Regexp.last_match(2), terminal:)
    "#{indent}#{terminal.accent("")} #{content}"
  when NUMBERED_RE
    indent = ::Regexp.last_match(1)
    num = ::Regexp.last_match(2)
    content = render_inline(::Regexp.last_match(3), terminal:)
    "#{indent}#{terminal.accent("#{num}.")} #{content}"
  else
    render_inline(line, terminal:)
  end
end

.visual_width(text) ⇒ Object



54
55
56
# File 'lib/rixie/cli/markdown.rb', line 54

def visual_width(text)
  text.gsub(/\*+/, "").each_char.sum { |c| (c.bytesize > 1) ? 2 : 1 }
end