Fixed escaping during autolink

Implementing the HTML escaping code manually is necessary to avoid the
following exception during testing:

Method escapeHtml in android.text.Html not mocked
pull/147/head
Roland Illig 7 years ago
parent 0b3fde5ee3
commit 9b62804ed6

@ -127,15 +127,22 @@ public class HtmlHelper {
static String autolink(String text) { static String autolink(String text) {
Matcher matcher = pattern.matcher(text); Matcher matcher = pattern.matcher(text);
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
int end = 0;
while (matcher.find()) { while (matcher.find()) {
String ref = matcher.group(); sb.append(html(text.substring(end, matcher.start())));
matcher.appendReplacement(sb, String.format("<a href=\"%s\">%s</a>", ref, ref)); String ref = html(matcher.group());
sb.append(String.format("<a href=\"%s\">%s</a>", ref, ref));
end = matcher.end();
} }
matcher.appendTail(sb); sb.append(text.substring(end));
return sb.toString(); return sb.toString();
} }
private static String html(String plain) {
return plain.replace("&", "&amp;").replace("<", "&lt;");
}
static Drawable decodeImage(String source, Context context, long id, boolean show) { static Drawable decodeImage(String source, Context context, long id, boolean show) {
int px = Helper.dp2pixels(context, 48); int px = Helper.dp2pixels(context, 48);

@ -28,10 +28,10 @@ class HtmlHelperTest {
testAutolink( testAutolink(
"https://example.org/search?q=%C3%A4&hl=nl", "https://example.org/search?q=%C3%A4&hl=nl",
// TODO: Strictly speaking, the & should be encoded as &amp;. // The & should be encoded as &amp;, even though
// Most browsers can deal with this situation though. // most browsers can deal with this situation.
"<a href=\"https://example.org/search?q=%C3%A4&hl=nl\">" + "<a href=\"https://example.org/search?q=%C3%A4&amp;hl=nl\">" +
"https://example.org/search?q=%C3%A4&hl=nl</a>" "https://example.org/search?q=%C3%A4&amp;hl=nl</a>"
); );
testAutolink( testAutolink(
@ -43,8 +43,8 @@ class HtmlHelperTest {
testAutolink( testAutolink(
"Go to <http://example.org/>.", "Go to <http://example.org/>.",
// FIXME: The < must be encoded as &lt;. // The < must be encoded as &lt;, to avoid confusion.
"Go to <<a href=\"http://example.org/\">http://example.org/</a>>." "Go to &lt;<a href=\"http://example.org/\">http://example.org/</a>>."
); );
testAutolink( testAutolink(

Loading…
Cancel
Save