/** * Nasty method for extracting doc sections from a markdown document. * * <ol> * <li>The most prominent heading(s) are identified * <li>The document is split into a list of sections corresponding to the tree following * headings of that level. If the document didn't begin with a heading of that level, the * first Section in the result list will have a null heading. * </ol> * * @param document * @return */ public static List<Section> extractSections(Document document) { SectionsMarkdownVisitor v = new SectionsMarkdownVisitor(); document.accept(v); List<Section> result = new ArrayList<>(); for (int levelIndex = 1; levelIndex <= 6; levelIndex++) { List<Header> sections = v.sections.get(levelIndex); if (sections != null) { Node parent; { Header header = sections.get(0); parent = header.jjtGetParent(); Document doc = extractBetween(v, parent, null, header); result.add(new Section(null, doc)); } for (int sectionIndex = 0; sectionIndex < sections.size(); sectionIndex++) { Header header = sections.get(sectionIndex); Header next = sectionIndex < sections.size() - 1 ? sections.get(sectionIndex + 1) : null; Document doc = extractBetween(v, parent, header, next); result.add(new Section(header, doc)); } break; } } return result; }
/** Constructs a Header */ static Header header(int level, String text) { Header header = new Header(Parser.JJTHEADER); header.setLevel(level); Text t = new Text(Parser.JJTTEXT); t.jjtSetValue(text); header.jjtAddChild(t, 0); return header; }
@Override public void visit(Header arg0) { List<Header> headers = sections.get(arg0.getLevel()); if (headers == null) { headers = new ArrayList<>(); sections.put(arg0.getLevel(), headers); } headers.add(arg0); }