Skip to content

Commit 4b8419b

Browse files
committed
Fix link text being escaped when a tag contains an img tag
1 parent ee245d8 commit 4b8419b

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/ReverseMarkdown.Test/ConverterTests.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1320,5 +1320,13 @@ public void WhenBoldTagContainsBRTag_ThenConvertToMarkdown()
13201320
var expected = $"test** {Environment.NewLine}test**";
13211321
CheckConversion(html, expected);
13221322
}
1323+
1324+
[Fact]
1325+
public void WhenAnchorTagContainsImgTag_LinkTextShouldNotBeEscaped()
1326+
{
1327+
const string html = "<a href=\"https://www.example.com\"><img src=\"https://example.com/image.jpg\"/></a>";
1328+
var expected = $"[![](https://example.com/image.jpg)](https://www.example.com)";
1329+
CheckConversion(html, expected);
1330+
}
13231331
}
13241332
}

src/ReverseMarkdown/Converters/A.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using HtmlAgilityPack;
22
using System;
3+
using System.Linq;
34

45
namespace ReverseMarkdown.Converters {
56
public class A : ConverterBase
@@ -14,6 +15,8 @@ public override string Convert(HtmlNode node)
1415
{
1516
var name = TreatChildren(node).Trim();
1617

18+
var hasSingleChildImgNode = node.ChildNodes.Count == 1 && node.ChildNodes.Count(n => n.Name.Contains("img")) == 1;
19+
1720
var href = node.GetAttributeValue("href", string.Empty).Trim().Replace("(", "%28").Replace(")", "%29").Replace(" ", "%20");
1821
var title = ExtractTitle(node);
1922
title = title.Length > 0 ? $" \"{title}\"" : "";
@@ -41,7 +44,10 @@ public override string Convert(HtmlNode node)
4144
(scheme.Equals("http", StringComparison.OrdinalIgnoreCase) || scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
4245
&& string.Equals(href, $"{scheme}://{name}", StringComparison.OrdinalIgnoreCase);
4346

44-
return useHrefWithHttpWhenNameHasNoScheme ? href : $"[{StringUtils.EscapeLinkText(name)}]({href}{title})";
47+
// if the anchor tag contains a single child image node don't escape the link text
48+
var linkText = hasSingleChildImgNode ? name : StringUtils.EscapeLinkText(name);
49+
50+
return useHrefWithHttpWhenNameHasNoScheme ? href : $"[{linkText}]({href}{title})";
4551
}
4652
}
4753
}

0 commit comments

Comments
 (0)