aboutsummaryrefslogtreecommitdiff
path: root/_plugins/add-anchor-to-code-block-line-numbers.rb
blob: ec6f0a8d8f65d0e95bb8c793c4d93695af3d4e4f (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
PREFIX = '<pre class="lineno">'
POSTFIX = '</pre>'
Jekyll::Hooks.register [:documents, :pages], :post_render do |doc|
  if doc.output_ext == ".html" && doc.type != :slides
    code_block_counter = 1
    doc.output = doc.output.gsub(/<pre class="lineno">[\n0-9]+<\/pre>/) do |match|
      line_numbers = match
                      .gsub(/<pre class="lineno">([\n0-9]+)<\/pre>/, '\1')
                      .split("\n")

      anchored_line_numbers_array = line_numbers.map do |n|
        id = "B#{code_block_counter}-L#{n}"
        "<a class=\"code-line-anchor\" id=\"#{id}\" href=\"##{id}\">#{n}</a>"
      end
      code_block_counter += 1

      PREFIX + anchored_line_numbers_array.join("\n") + POSTFIX
    end
  end
end