diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index 954ca7df25cac..6690e025c6cf7 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -534,7 +534,12 @@ def set_cycle(name, cycle_object)
AUTO_LINK_RE = %r{
(?: ([\w+.:-]+:)// | www\. )
[^\s<]+
- }x unless const_defined?(:AUTO_LINK_RE)
+ }x
+
+ # regexps for determining context, used high-volume
+ AUTO_LINK_CRE = [/<[^>]+$/, /^[^>]*>/, //i, /<\/a>/i]
+
+ AUTO_EMAIL_RE = /[\w.!#\$%+-]+@[\w-]+(?:\.[\w-]+)+/
BRACKETS = { ']' => '[', ')' => '(', '}' => '{' }
@@ -545,9 +550,8 @@ def auto_link_urls(text, html_options = {})
text.gsub(AUTO_LINK_RE) do
scheme, href = $1, $&
punctuation = ''
- left, right = $`, $'
- # detect already linked URLs and URLs in the middle of a tag
- if left =~ /<[^>]+$/ && right =~ /^[^>]*>/
+
+ if auto_linked?($`, $')
# do not change string; URL is already linked
href
else
@@ -570,11 +574,10 @@ def auto_link_urls(text, html_options = {})
# Turns all email addresses into clickable links. If a block is given,
# each email is yielded and the result is used as the link text.
def auto_link_email_addresses(text, html_options = {})
- body = text.dup
- text.gsub(/([\w\.!#\$%\-+.]+@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)+)/) do
- text = $1
+ text.gsub(AUTO_EMAIL_RE) do
+ text = $&
- if body.match(/]*>(.*)(#{Regexp.escape(text)})(.*)<\/a>/)
+ if auto_linked?($`, $')
text
else
display_text = (block_given?) ? yield(text) : text
@@ -582,6 +585,12 @@ def auto_link_email_addresses(text, html_options = {})
end
end
end
+
+ # Detects already linked context or position in the middle of a tag
+ def auto_linked?(left, right)
+ (left =~ AUTO_LINK_CRE[0] and right =~ AUTO_LINK_CRE[1]) or
+ (left.rindex(AUTO_LINK_CRE[2]) and $' !~ AUTO_LINK_CRE[3])
+ end
end
end
end
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index 6ee7faaf86922..d40d021166dbf 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -296,6 +296,7 @@ def test_auto_linking
assert_equal %( Link #{link_result_with_options} Link #{link_raw} Go to #{link_result}, then say hello to #{email_result}. Go to #{link_raw}, then say hello to #{email_raw}.
#{url[0...7]}...
#{email[0...7]}...
#{url}
#{email}