Module: Aspera::Markdown
Overview
Formatting for Markdown
Constant Summary collapse
- INLINE_MARKUP_RE =
Matches: bold,
code, or an HTML entity (&, ©, 💩) /(?:\*\*(?<bold>[^*]+?)\*\*)|(?:`(?<code>[^`]+)`)|&(?<entity>(?:[A-Za-z][A-Za-z0-9]{1,31}|#\d{1,7}|#x[0-9A-Fa-f]{1,6}));/m- HTML_BREAK =
HTML line-break tag used in Markdown table cells to separate multi-line values.
'<br/>'- HEADING_RE =
Matches a Markdown heading line (e.g.
## Title); group 1 =#chars, group 2 = text. /^(\#{1,6})[ \t]+(\S.*)$/- FENCE_RE =
Matches the start or end of a fenced code block; group 1 = fence (``` or ~~~).
/^ {0,3}(`{3,}|~{3,})/- COL_WIDTH =
Maximum column width (in characters) for generated Markdown tables.
80- ADMONITION_TYPES =
Accepted admonition types.
%w[NOTE CAUTION WARNING IMPORTANT TIP INFO].freeze
Instance Method Summary collapse
-
#admonition(lines, type: 'INFO') ⇒ String
Generate a GitHub-flavoured admonition block.
-
#code(lines, type: 'shell') ⇒ String
Generate a fenced code block.
-
#each_line_with_heading(content) {|line, heading| ... } ⇒ Object
Iterate on the lines of a Markdown document, with the heading match of each line.
-
#extract_section(content, anchor) ⇒ String?
Extract the content of a single section (heading + body until next heading of same/higher level).
-
#heading(title, level: 1) ⇒ String
Generate a markdown heading.
-
#heading_to_anchor(text, seen: nil) ⇒ String
Convert a Markdown heading text to a GitHub-flavoured anchor.
-
#icode(text) ⇒ String
Wrap text in inline code backticks.
-
#list(items) ⇒ String
Generate markdown list from the provided list.
-
#paragraph(text) ⇒ String
Wrap text in a markdown paragraph (trailing blank line).
-
#table(table) ⇒ String
Generate markdown from the provided 2D table.
-
#toc(content, max_level: nil) ⇒ Array<Hash>
Extract the table of contents from a Markdown document.
Instance Method Details
#admonition(lines, type: 'INFO') ⇒ String
Generate a GitHub-flavoured admonition block
151 152 153 154 |
# File 'lib/aspera/markdown.rb', line 151 def admonition(lines, type: 'INFO') Aspera.assert_values(type, ADMONITION_TYPES) { 'admonition type' } paragraph((["[!#{type}]"] + lines).map { |l| "> #{l}" }.join("\n")) end |
#code(lines, type: 'shell') ⇒ String
Generate a fenced code block
143 144 145 |
# File 'lib/aspera/markdown.rb', line 143 def code(lines, type: 'shell') paragraph("```#{type}\n#{lines.join("\n")}\n```") end |
#each_line_with_heading(content) {|line, heading| ... } ⇒ Object
Iterate on the lines of a Markdown document, with the heading match of each line.
A line in a fenced code block is not a heading (e.g. a shell comment # ...).
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/aspera/markdown.rb', line 56 def each_line_with_heading(content) fence = nil content.each_line do |line| if (f = line.match(FENCE_RE)) # a code block ends with the same kind of fence, at least as long, without info string if fence.nil? fence = f[1] elsif f[1].start_with?(fence) && line.strip.eql?(f[1]) fence = nil end yield(line, nil) else yield(line, fence.nil? ? line.match(HEADING_RE) : nil) end end end |
#extract_section(content, anchor) ⇒ String?
Extract the content of a single section (heading + body until next heading of same/higher level).
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/aspera/markdown.rb', line 94 def extract_section(content, anchor) seen = {} section_level = nil result = [] each_line_with_heading(content) do |line, m| if m slug = heading_to_anchor(m[2].strip, seen: seen) if section_level.nil? # not yet found: check if this heading matches next unless slug == anchor section_level = m[1].length elsif m[1].length <= section_level # already in section: stop at same/higher level heading break end end result << line if section_level end result.empty? ? nil : result.join end |
#heading(title, level: 1) ⇒ String
Generate a markdown heading
135 136 137 |
# File 'lib/aspera/markdown.rb', line 135 def heading(title, level: 1) paragraph("#{'#' * level} #{title}") end |
#heading_to_anchor(text, seen: nil) ⇒ String
Convert a Markdown heading text to a GitHub-flavoured anchor. Rules: downcase, keep letters/digits/spaces/hyphens, replace spaces with hyphens. Duplicate anchors are disambiguated by appending -1, -2, … (pass a seen Hash to track).
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/aspera/markdown.rb', line 34 def heading_to_anchor(text, seen: nil) slug = text .downcase .gsub(/[`*_]/, '') # strip inline code/bold/italic markers .gsub(/&[a-z]+;/, '') # strip HTML entities .gsub(/[^\w\s-]/, '') # keep word chars, spaces, hyphens .gsub(/\s+/, '-') # spaces → hyphens .squeeze('-') # collapse consecutive hyphens .strip if seen count = seen[slug].to_i seen[slug] = count + 1 slug = "#{slug}-#{count}" if count > 0 end slug end |
#icode(text) ⇒ String
Wrap text in inline code backticks
120 121 122 |
# File 'lib/aspera/markdown.rb', line 120 def icode(text) "`#{text}`" end |
#list(items) ⇒ String
Generate markdown list from the provided list
159 160 161 |
# File 'lib/aspera/markdown.rb', line 159 def list(items) items.map { |i| "- #{i}" }.join("\n") end |
#paragraph(text) ⇒ String
Wrap text in a markdown paragraph (trailing blank line)
127 128 129 |
# File 'lib/aspera/markdown.rb', line 127 def paragraph(text) "#{text}\n\n" end |
#table(table) ⇒ String
Generate markdown from the provided 2D table
166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
# File 'lib/aspera/markdown.rb', line 166 def table(table) # get max width of each columns col_widths = table.transpose.map do |col| [col.flat_map { |c| c.to_s.delete('`').split(HTML_BREAK).map(&:size) }.max, COL_WIDTH].min end # do not modify caller's table table = table.dup headings = table.shift table.unshift(col_widths.map { |col_width| '-' * col_width }) table.unshift(headings) # Separator row with spaces around pipes, as other rows (markdownlint MD060, style `compact`) lines = table.map { |line| "| #{line.map { |i| i.to_s.gsub('\\', '\\\\').gsub('|', '\|') }.join(' | ')} |\n" } return lines.join.chomp end |
#toc(content, max_level: nil) ⇒ Array<Hash>
Extract the table of contents from a Markdown document.
77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/aspera/markdown.rb', line 77 def toc(content, max_level: nil) seen = {} result = [] each_line_with_heading(content) do |_line, m| next unless m title = m[2].strip # anchor of every heading, so that duplicate anchors are numbered as in the whole document anchor = heading_to_anchor(title, seen: seen) result.push({'level' => m[1].length, 'title' => title, 'anchor' => anchor}) if max_level.nil? || m[1].length <= max_level end result end |