Skip to content

Instantly share code, notes, and snippets.

@jmini
Last active February 15, 2019 23:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmini/230e5d4be48c1a0533eb to your computer and use it in GitHub Desktop.
Save jmini/230e5d4be48c1a0533eb to your computer and use it in GitHub Desktop.
Workaround for Asciidoctor #858 (fix the HTML Ouptu)
//Workaround using JSoup to obtain the desired behavior described in #858 for the HTML output.
//see https://github.com/asciidoctor/asciidoctor/issues/858
static private Pattern pattern = Pattern.compile("Figure ([0-9]+)\\.");
/**
* Main method for the #858 workaround.
*
* @param doc
* JSoup document (type is {@link org.jsoup.nodes.Document})
*/
public static void fixFigureLink(Document doc) {
Elements elements = doc.getElementsByTag("a");
for (Element link : elements) {
String href = link.attr("href");
if (href != null && href.startsWith("#")) {
String id = href.substring(1);
Element idElement = doc.getElementById(id);
boolean fixedText = false;
if (idElement != null && "imageblock".equals(idElement.attr("class"))) {
fixedText = fixLink(link, idElement);
}
//Support for the multiple Images in one figure workaround (see Issue 1287)
if (!fixedText && idElement != null) {
Element container = idElement.parent();
boolean checkNext = false;
for (int i = 0; i < container.childNodeSize(); i++) {
Node childNode = container.childNode(i);
if (id.equals(childNode.attr("id")) && "imageblock".equals(childNode.attr("class"))) {
checkNext = true;
}
if (!fixedText && checkNext) {
if ("imageblock".equals(childNode.attr("class")) && childNode instanceof Element) {
fixedText = fixLink(link, (Element) childNode);
}
else if (!(childNode instanceof Element)) {
//do nothing.
}
else {
//found an other element that does not correspond.
checkNext = false;
}
}
}
}
}
}
}
private static boolean fixLink(Element link, Element element) {
Element titleDiv = findTitleDiv(element);
if (titleDiv != null) {
Matcher matcher = pattern.matcher(titleDiv.text());
if (matcher.find()) {
link.text("Figure " + matcher.group(1));
return true;
}
}
return false;
}
private static Element findTitleDiv(Element element) {
Elements elements = element.getElementsByTag("div");
for (Element e : elements) {
if ("imageblock".equals(e.attr("class"))) {
return e;
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment