Module: GitlabKramdown::Parser::Autolink

Included in:
Kramdown::Parser::GitlabKramdown
Defined in:
lib/gitlab_kramdown/parser/autolink.rb

Overview

URL auto-linking

This parser implements URL auto-linking support for the most widely used schemas

Constant Summary collapse

PUNCTUATION_PAIRS =
/['"][)\]}][(\[{]/
ACHARS =
/[[:alnum:]]_/
%r{
  (?<uri>
    (?<schema>mailto|https?|ftps?|irc|smb):
    [^\s\[\]>]+
    (?<!\?|!|\.|,|:)
  |
    [-.#{ACHARS}]+@[-#{ACHARS}]+(?:\.[-#{ACHARS}]+)*\.[a-z]+
  )
}x

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



24
25
26
27
28
# File 'lib/gitlab_kramdown/parser/autolink.rb', line 24

def self.included(klass)
  return if klass.has_parser?(:gitlab_autolink)

  klass.define_parser(:gitlab_autolink, AUTOLINK_START)
end

Instance Method Details

Parse the autolink at the current location.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/gitlab_kramdown/parser/autolink.rb', line 31

def parse_gitlab_autolink
  start_line_number = @src.current_line_number
  @src.pos += @src.matched_size

  # current StringScanner has limitations that prevent lookbehind to work properly
  # so we can't use something like this: `(?<!\[)(?<!\]\()`. Using a negative lookbehind
  # would improve performance on the cases where it would prevent a match.
  #
  # There is an alternative we could explore: https://github.com/luikore/zscan which
  # does fix the current limitations, but them we are depending on another third party gem.
  #
  # Instead of depending on a third party, I'm opting for a simple fix that achieve the same
  # results but without the performance improvements:
  if @src.pre_match.end_with?('[', '](')
    add_text(@src[:uri])

    return
  end

  href = (@src[:schema].nil? ? "mailto:#{@src[:uri]}" : @src[:uri])
  el = Kramdown::Element.new(:a, nil, { 'href' => href }, location: start_line_number)

  add_text(@src[:uri].sub(/^mailto:/, ''), el)
  @tree.children << el
end