Add AutoLinkOptions.AllowDomainWithoutPeriod

This commit is contained in:
James Newton-King
2025-03-17 07:46:23 +08:00
parent fb3fe8b261
commit 39b07d6bc5
4 changed files with 30 additions and 3 deletions

View File

@@ -0,0 +1,22 @@
using Markdig.Extensions.AutoLinks;
namespace Markdig.Tests;
[TestFixture]
public class TestAutoLinks
{
[Test]
[TestCase("https://localhost", "<p><a href=\"https://localhost\">https://localhost</a></p>")]
[TestCase("http://localhost", "<p><a href=\"http://localhost\">http://localhost</a></p>")]
[TestCase("https://l", "<p><a href=\"https://l\">https://l</a></p>")]
[TestCase("www.l", "<p><a href=\"http://www.l\">www.l</a></p>")]
public void TestLinksWithAllowDomainWithoutPeriod(string markdown, string expected)
{
var pipeline = new MarkdownPipelineBuilder()
.UseAutoLinks(new AutoLinkOptions { AllowDomainWithoutPeriod = true })
.Build();
var html = Markdown.ToHtml(markdown, pipeline);
Assert.That(html, Is.EqualTo(expected).IgnoreWhiteSpace);
}
}

View File

@@ -22,4 +22,9 @@ public class AutoLinkOptions
/// Should a www link be prefixed with https:// instead of http:// (false by default)
/// </summary>
public bool UseHttpsForWWWLinks { get; set; }
/// <summary>
/// Should a link host name with no period, e.g. https://localhost, be allowed (false by default)
/// </summary>
public bool AllowDomainWithoutPeriod { get; set; }
}

View File

@@ -164,7 +164,7 @@ public class AutoLinkParser : InlineParser
}
// Do not need to check if a telephone number is a valid domain
if (c != 't' && !LinkHelper.IsValidDomain(link, domainOffset))
if (c != 't' && !LinkHelper.IsValidDomain(link, domainOffset, Options.AllowDomainWithoutPeriod))
{
return false;
}

View File

@@ -1006,7 +1006,7 @@ public static class LinkHelper
return c == '\0' || c.IsSpaceOrTab() || c.IsControl() || (isAutoLink && c == '<'); // TODO: specs unclear. space is strict or relaxed? (includes tabs?)
}
public static bool IsValidDomain(string link, int prefixLength)
public static bool IsValidDomain(string link, int prefixLength, bool allowDomainWithoutPeriod)
{
// https://github.github.com/gfm/#extended-www-autolink
// A valid domain consists of alphanumeric characters, underscores (_), hyphens (-) and periods (.).
@@ -1052,7 +1052,7 @@ public static class LinkHelper
segmentHasCharacters = true;
}
return segmentCount != 1 && // At least one dot was present
return (segmentCount != 1 || allowDomainWithoutPeriod) && // At least one dot was present
segmentHasCharacters && // Last segment has valid characters
segmentCount - lastUnderscoreSegment >= 2; // No underscores are present in the last two segments of the domain
}