TableOfContentsMacro extends AbstractMarkdownMacroRunnable { @Override String getMarkdown(IMacroContext macroContext) { HtmlSerializerContext context = macroContext.getHtmlSerializerContext(); List<Header> headers = context.getHeaders(); if (!headers.isEmpty()) { int smallestLevel = Integer.MAX_VALUE; for (Header header : headers) { int level = header.getLevel() - 1; if (level < smallestLevel) { smallestLevel = level; } } StringBuilder buf = new StringBuilder(); for (Header header : headers) { buf.append(StringUtils.repeat(" ", header.getLevel() - 1 - smallestLevel)) .append("- [[#").append(header.getText()).append("]]\n"); } return buf.toString() + "\n"; } return null; }    }
@Test public void getMarkdown() { List<Header> headers = Lists.newArrayList( new Header("foo", 1), new Header("bar", 2), new Header("baz", 3), new Header("qux", 1)); when(htmlSerializerContext.getHeaders()).thenReturn(headers); assertEquals( "- [[#foo]]\n" + " - [[#bar]]\n" + " - [[#baz]]\n" + "- [[#qux]]\n\n", runnable.getMarkdown(context)); }
@Test public void getMarkdownButNoHeaders() { List<Header> headers = Collections.emptyList(); when(htmlSerializerContext.getHeaders()).thenReturn(headers); assertNull(runnable.getMarkdown(context)); }