Last active
February 15, 2019 23:41
-
-
Save jmini/230e5d4be48c1a0533eb to your computer and use it in GitHub Desktop.
Workaround for Asciidoctor #858 (fix the HTML Ouptu)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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