Module: Aspera::Markdown

Extended by:
Markdown
Included in:
Markdown
Defined in:
lib/aspera/markdown.rb

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

Instance Method Details

#admonition(lines, type: 'INFO') ⇒ String

Generate a GitHub-flavoured admonition block

Parameters:

Returns:

  • (String) —

    markdown 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

Parameters:

  • lines (Array<String>) —

    lines of code

  • type (String) (defaults to: 'shell') —

    language identifier for syntax highlighting

Returns:

  • (String) —

    markdown 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 # ...).

Parameters:

  • content (String) —

    full Markdown source

Yield Parameters:

  • line (String) —

    the line

  • heading (MatchData, nil) —

    match of HEADING_RE, or nil if not a heading



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).

Parameters:

  • content (String) —

    full Markdown source

  • anchor (String) —

    GitHub anchor slug (without #)

Returns:

  • (String, nil) —

    the section content, or nil if not found



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

Parameters:

  • title (String) —

    heading text

  • level (Integer) (defaults to: 1) —

    heading level (1–6)

Returns:

  • (String) —

    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).

Parameters:

  • text (String) —

    raw heading text (without leading # and spaces)

  • seen (Hash{String=>Integer}, nil) (defaults to: nil) —

    mutable counter; pass the same Hash across a document

Returns:

  • (String) —

    anchor slug (without leading #)



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

Parameters:

  • text (String) —

    text to wrap

Returns:

  • (String) —

    inline code span



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

Parameters:

  • items (Array<String>) —

    list of items

Returns:

  • (String) —

    markdown unordered 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)

Parameters:

  • text (String) —

    paragraph content

Returns:

  • (String) —

    paragraph with trailing newlines



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

Parameters:

  • table (Array<Array<String>>) —

    2D array of strings

Returns:



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.

Parameters:

  • content (String) —

    full Markdown source

  • max_level (Integer, nil) (defaults to: nil) —

    maximum level of headings, or nil for all

Returns:

  • (Array<Hash>) —

    array of { level, title, anchor } (String keys, as other results: --select applies)



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