+ public void addChild(Heading heading){
+ children.add(heading);
+ }
+
+ public List<Heading> getChildren(){
+ return children;
+ }
+
+ public String toMD () {
+ StringBuilder sb = new StringBuilder();
+
+ if (level > 0) sb.append(enlistTitleInMD());
+
+ rootListElement.toMD(sb, -2);
+
+ children.stream().map(Heading::toMD).forEach(sb::append);
+
+ return sb.toString();
+ }
+
+ private String enlistTitleInMD() {
+ String2 s = new String2();
+ s.append("#", level).append(" ").append(name.toMD(0)).append("\n");
+ return s.toString();
+ }
+
+ public ListElement getCurrentHeading(){
+ return currentListElement;
+ }
+
+ public void parse(TokenizerMatch tm){
+
+ int indent = Utils.getLineIndent(tm.token);
+ if (indent > -1 && indent <= currentListElement.indent) handleListDepthDecrease(indent);
+
+ if (tm.isGroup(TG_LIST)){
+ parseList(tm);
+ return;
+ }
+
+ currentListElement.parse(tm);
+ }
+
+ private void handleListDepthDecrease(int indent) {
+ while (true){
+ if (currentListElement.parent.indent <= indent){
+ currentListElement = currentListElement.parent;
+ return;
+ }
+ currentListElement = currentListElement.parent;
+ }
+ }
+
+ private void parseList(TokenizerMatch tm) {
+ String[] listSections = tm.getRegExpGroups();
+ int indent = listSections[0].length();
+ String type = listSections[1];
+
+ String title = getPartialTitle(listSections);
+
+ if (indent > currentListElement.indent){
+ // list dept increases
+ ListElement newElement = new ListElement(title, indent, currentListElement, type);
+ currentListElement.addContent(newElement);
+ currentListElement = newElement;
+ return;
+ }
+
+ if (indent > currentListElement.parent.indent){
+ // list depth is the same
+ ListElement newElement = new ListElement(title, indent, currentListElement.parent, type);
+ currentListElement.parent.addContent(newElement);
+ currentListElement = newElement;
+ return;
+ }
+
+ throw new RuntimeException("Impossible condition reached. Must be a bug!");
+ }
+
+ private String getPartialTitle(String[] listSections) {
+ return listSections.length > 2 ? listSections[2] : "";
+ }
+