TextUtils { protected static String markdownToHtml(String text) { text = text.replaceAll("<([^a-zA-Z/])", "&lt;$1"); text = ReplaceCallback.replace("(?s)<\\s?span([^\\/\n]*)>((?:(?!<\\/).)+)<\\/\\s?span\\s?>", text, createSpan); text = text.replaceAll("(?s)\\\\#", "&#35;"); text = text.replaceAll("(?s)\\\\\\\\", "&#92;"); text = text.replaceAll("(?s)\\\\_", "&#95;"); text = text.replaceAll("(?s)\\\\\\*", "&#42;"); text = text.replaceAll("(?s)__(.*?)__", "<strong>$1</strong>"); text = text.replaceAll("(?s)\\*\\*(.*?)\\*\\*", "<strong>$1</strong>"); text = text.replaceAll("(?s)_([^\\s][^_\n]*)_", "<em>$1</em>"); text = text.replaceAll("(?s)\\*([^\\s][^\\*\n]*)\\*", "<em>$1</em>"); text = text.replaceAll("(?s)\\[([^\\]]*)\\]\\(([^\\)]+)\\)", "<a href=\"$2\" target=\"_blank\">$1</a>"); text = ReplaceCallback.replace("(?s)^(#+)([^\n]*)$", text, createHeader); text = ReplaceCallback.replace("(?s)([^\n]+)\n", text, createParagraph); text = text.replaceAll("(?s)&#35;", "#"); text = text.replaceAll("(?s)&#42;", "*"); text = text.replaceAll("(?s)&#95;", "_"); text = text.replaceAll("(?s)&#92;", "\\\\"); return text; } private  TextUtils(); static CharSequence textToHtml(String text); static String ellipsizeBeginning(String text); static String join(@NonNull CharSequence delimiter, @NonNull Iterable tokens);  }
@Test public void markDownToHtmlEscapesBackslash() { String[][] tests = { {"A\\_B\\_C", "A_B_C"}, {"_A\\_B\\_C_", "<em>A_B_C</em>"}, {"A_B\\_C", "A_B_C"}, {"A\\_B_C", "A_B_C"}, {"A_B_C", "A<em>B</em>C"}, {"\\__AB\\__", "_<em>AB_</em>"}, {"\\\\_AB\\_\\\\_", "\\<em>AB_\\</em>"}, {"A\\*B\\*C", "A*B*C"}, {"*A\\*B\\*C*", "<em>A*B*C</em>"}, {"A*B\\*C", "A*B*C"}, {"A*B*C", "A<em>B</em>C"}, {"\\**AB\\**", "*<em>AB*</em>"}, {"\\\\*AB\\*\\\\*", "\\<em>AB*\\</em>"}, {"\\a\\ b\\*c\\d\\_e", "\\a\\ b*c\\d_e"}, {"\\#1", "#1"}, {"\\#\\# 2", "## 2"}, {"works \\#when not required too", "works #when not required too"}, {"\\", "\\"}, {"\\\\", "\\"}, {"\\\\\\", "\\\\"}}; for (String[] testCase : tests) { assertEquals(testCase[1], TextUtils.markdownToHtml(testCase[0])); } }
@Test public void markDownToHtml_EscapesLessThan() { String[][] tests = { {"<1", "&lt;1"}, {"<1>", "&lt;1>"}, {"< span>", "&lt; span>"}, {"< 1", "&lt; 1"}, {"< 1/>", "&lt; 1/>"}, {"test< 1/>", "test&lt; 1/>"}, {"test < 1/>", "test &lt; 1/>"} }; for (String[] testCase: tests) { assertEquals(testCase[1], TextUtils.markdownToHtml(testCase[0])); } }
@Test public void markDownToHtml_SupportsHtml() { String[] tests = { "<span", "<span>", "<notarealtag>", "<CAPSTAG", "</closetag>" }; for (String testCase: tests) { assertEquals(testCase, TextUtils.markdownToHtml(testCase)); } }