Module: Agentilda::Markdown

Defined in:
lib/agentilda/markdown.rb

Overview

The smallest Markdown reader that covers what plan folders actually hold. No CommonMark ambitions: it needs to find a GFM table and split its rows.

Class Method Summary collapse

Class Method Details

.cells(row) ⇒ Array<String>

Split a table row into stripped cells.

Parameters:

  • row (String)

    a line beginning, and usually ending, with |

Returns:

  • (Array<String>)


13
14
15
# File 'lib/agentilda/markdown.rb', line 13

def cells(row)
  row.strip.sub(/\A\|/, "").sub(/\|\z/, "").split(/(?<!\\)\|/).map(&:strip)
end

.delimiter_row?(row) ⇒ Boolean

Returns whether this is a |---|:--:| alignment row.

Parameters:

  • row (String)

Returns:

  • (Boolean)

    whether this is a |---|:--:| alignment row



19
20
21
22
# File 'lib/agentilda/markdown.rb', line 19

def delimiter_row?(row)
  parsed = cells(row)
  !parsed.empty? && parsed.all? { |c| c.match?(/\A:?-+:?\z/) }
end

.tables(text) ⇒ Array<Hash{Symbol => Array}>

Every GFM table in the document, in order.

Parameters:

  • text (String)

Returns:

  • (Array<Hash{Symbol => Array}>)

    {header:, rows:}



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
# File 'lib/agentilda/markdown.rb', line 28

def tables(text)
  lines = text.to_s.lines(chomp: true)
  found = []
  index = 0

  while index < lines.length
    head = lines[index]
    rule = lines[index + 1]

    unless head&.strip&.start_with?("|") && rule&.strip&.start_with?("|") && delimiter_row?(rule)
      index += 1
      next
    end

    body = []
    cursor = index + 2
    while cursor < lines.length && lines[cursor].strip.start_with?("|")
      body << cells(lines[cursor])
      cursor += 1
    end

    found << {header: cells(head), rows: body}
    index = cursor
  end

  found
end