Improved plain text formatting

pull/162/head
M66B 5 years ago
parent 86259d7286
commit d869731306

@ -620,15 +620,15 @@ public class HtmlHelper {
NodeTraversor.traverse(new NodeVisitor() { NodeTraversor.traverse(new NodeVisitor() {
private int qlevel = 0; private int qlevel = 0;
private int tlevel = 0; private int tlevel = 0;
private boolean nl = true;
public void head(Node node, int depth) { public void head(Node node, int depth) {
if (node instanceof TextNode) { if (node instanceof TextNode)
append(((TextNode) node).text()); append(((TextNode) node).text());
append(" "); else {
} else {
String name = node.nodeName(); String name = node.nodeName();
if ("li".equals(name)) if ("li".equals(name))
append("* "); append("*");
else if ("blockquote".equals(name)) else if ("blockquote".equals(name))
qlevel++; qlevel++;
@ -639,15 +639,11 @@ public class HtmlHelper {
public void tail(Node node, int depth) { public void tail(Node node, int depth) {
String name = node.nodeName(); String name = node.nodeName();
if ("a".equals(name)) { if ("a".equals(name))
append("["); append("[" + node.absUrl("href") + "] ");
append(node.absUrl("href")); else if ("img".equals(name))
append("] "); append("[" + node.absUrl("src") + "] ");
} else if ("img".equals(name)) { else if ("th".equals(name) || "td".equals(name)) {
append("[");
append(node.absUrl("src"));
append("] ");
} else if ("th".equals(name) || "td".equals(name)) {
Node next = node.nextSibling(); Node next = node.nextSibling();
if (next == null || !("th".equals(next.nodeName()) || "td".equals(next.nodeName()))) if (next == null || !("th".equals(next.nodeName()) || "td".equals(next.nodeName())))
newline(); newline();
@ -663,20 +659,22 @@ public class HtmlHelper {
newline(); newline();
tlevel = qlevel; tlevel = qlevel;
} }
if (!nl)
sb.append(" ");
sb.append(text); sb.append(text);
nl = false;
} }
private void newline() { private void newline() {
trimEnd(sb);
sb.append("\n"); sb.append("\n");
for (int i = 0; i < qlevel; i++) for (int i = 0; i < qlevel; i++)
sb.append('>'); sb.append('>');
if (qlevel > 0) if (qlevel > 0)
sb.append(' '); sb.append(' ');
nl = true;
} }
}, Jsoup.parse(html)); }, Jsoup.parse(html));
trimEnd(sb);
sb.append("\n"); sb.append("\n");
return sb.toString(); return sb.toString();
@ -730,13 +728,6 @@ public class HtmlHelper {
} }
} }
private static void trimEnd(StringBuilder sb) {
int length = sb.length();
while (length > 0 && sb.charAt(length - 1) == ' ')
length--;
sb.setLength(length);
}
static Spanned fromHtml(@NonNull String html) { static Spanned fromHtml(@NonNull String html) {
return fromHtml(html, null, null); return fromHtml(html, null, null);
} }

Loading…
Cancel
Save