
io.femo.commonmark.ext.AbbreviationDictionaryPostprocessor Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commonmark-ext-abbr Show documentation
Show all versions of commonmark-ext-abbr Show documentation
Extension that performs abbreviation detection like in python markdown
The newest version!
package io.femo.commonmark.ext;
import org.commonmark.node.*;
import org.commonmark.parser.PostProcessor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by felix on 8/1/16.
*/
public class AbbreviationDictionaryPostprocessor implements PostProcessor {
private static String regexAbbr = "\\*\\[(.*)\\]:(.*)";
private static Pattern pattern = Pattern.compile(regexAbbr);
@Override
public Node process(Node node) {
AbbreviationDictionaryVisitor visitor = new AbbreviationDictionaryVisitor();
node.accept(visitor);
return node;
}
private class AbbreviationDictionaryVisitor extends AbstractVisitor {
int inLink = 0;
@Override
public void visit(Link link) {
inLink++;
super.visit(link);
inLink--;
}
@Override
public void visit(Text text) {
if (inLink == 0) {
handle(text);
}
}
}
private class AbbreviationReplacerVisitor extends AbstractVisitor {
private String abbr;
private String descr;
int inLink = 0;
public AbbreviationReplacerVisitor(String abbr, String descr) {
this.abbr = abbr;
this.descr = descr;
}
@Override
public void visit(Link link) {
inLink++;
super.visit(link);
inLink--;
}
@Override
public void visit(Text text) {
if(inLink == 0) {
String literal = text.getLiteral();
if(literal.contains(abbr)) {
int index;
while ((index = literal.indexOf(abbr)) > 0) {
Abbreviation abbreviation = new Abbreviation(descr);
abbreviation.appendChild(new Text(abbr));
if(index > 0) {
String value = literal.substring(0, index);
text.insertBefore(new Text(value));
}
text.insertBefore(abbreviation);
literal = literal.substring(index + abbr.length());
}
text.insertBefore(new Text(literal));
text.unlink();
}
}
}
}
private void handle(Text text) {
String literal = text.getLiteral();
Matcher matcher = pattern.matcher(literal);
if(matcher.find()) {
String abbr, descr;
abbr = matcher.group(1).trim();
descr = matcher.group(2).trim();
Document document = document(text);
text.unlink();
document.accept(new AbbreviationReplacerVisitor(abbr, descr));
}
}
private Document document(Node node) {
Node parent = node;
while (!(parent instanceof Document)) parent = parent.getParent();
return (Document) parent;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy