Search in sources :

Example 1 with ValueRunnable

use of com.vladsch.flexmark.util.ValueRunnable in project flexmark-java by vsch.

the class TocUtils method renderMarkdownToc.

public static void renderMarkdownToc(HtmlWriter html, List<Heading> headings, List<String> headingTexts, final TocOptions tocOptions) {
    int initLevel = -1;
    int lastLevel = -1;
    final int[] headingNumbers = new int[7];
    final boolean[] openedItems = new boolean[7];
    Computable<String, Integer> listOpen = new Computable<String, Integer>() {

        @Override
        public String compute(Integer level) {
            openedItems[level] = true;
            if (tocOptions.isNumbered) {
                int v = ++headingNumbers[level];
                return v + ". ";
            } else {
                return "- ";
            }
        }
    };
    ValueRunnable<Integer> listClose = new ValueRunnable<Integer>() {

        @Override
        public void run(Integer level) {
            if (tocOptions.isNumbered) {
                headingNumbers[level] = 0;
            }
        }
    };
    if (headings.size() > 0 && !tocOptions.title.isEmpty()) {
        html.raw("######".substring(0, tocOptions.titleLevel)).raw(" ").raw(tocOptions.title).line();
    }
    for (int i = 0; i < headings.size(); i++) {
        Heading header = headings.get(i);
        String headerText = headingTexts.get(i);
        int headerLevel = tocOptions.listType != TocOptions.ListType.HIERARCHY ? 1 : header.getLevel();
        if (initLevel == -1) {
            initLevel = headerLevel;
            lastLevel = headerLevel;
        }
        if (lastLevel < headerLevel) {
            for (int lv = lastLevel; lv <= headerLevel - 1; lv++) {
                openedItems[lv + 1] = false;
            }
            html.indent();
        } else if (lastLevel == headerLevel) {
            if (i != 0) {
                html.line();
            }
        } else {
            for (int lv = lastLevel; lv >= headerLevel + 1; lv++) {
                if (openedItems[lv]) {
                    html.unIndent();
                    listClose.run(lv);
                }
            }
            html.line();
        }
        html.line().raw(listOpen.compute(headerLevel));
        html.raw(headerText);
        lastLevel = headerLevel;
    }
    html.line();
}
Also used : Heading(com.vladsch.flexmark.ast.Heading) ValueRunnable(com.vladsch.flexmark.util.ValueRunnable) Computable(com.vladsch.flexmark.util.Computable)

Aggregations

Heading (com.vladsch.flexmark.ast.Heading)1 Computable (com.vladsch.flexmark.util.Computable)1 ValueRunnable (com.vladsch.flexmark.util.ValueRunnable)1