diff --git a/core/src/main/kotlin/eu/iamgio/quarkdown/ast/iterator/ObservableAstIterator.kt b/core/src/main/kotlin/eu/iamgio/quarkdown/ast/iterator/ObservableAstIterator.kt index 1ed82728..01c3bf9a 100644 --- a/core/src/main/kotlin/eu/iamgio/quarkdown/ast/iterator/ObservableAstIterator.kt +++ b/core/src/main/kotlin/eu/iamgio/quarkdown/ast/iterator/ObservableAstIterator.kt @@ -22,6 +22,7 @@ class ObservableAstIterator : AstIterator { /** * Registers a hook that will be called when a node of type [T] is visited. * @param hook action to be called, with the visited node as parameter + * @param T desired node type * @return this for concatenation */ inline fun on(noinline hook: (T) -> Unit): ObservableAstIterator = @@ -39,6 +40,16 @@ class ObservableAstIterator : AstIterator { onFinishedHooks.add(hook) } + /** + * Collects all the visited nodes of type [T] into a collection. + * @param T node type + * @return an ordered list (DFS order) containing all the visited nodes of type [T] in the tree + */ + inline fun collectAll(): List = + mutableListOf().apply { + on(::add) + } + /** * Attaches a hook to this iterator. * @param hook hook to attach diff --git a/core/src/main/kotlin/eu/iamgio/quarkdown/context/hooks/TableOfContentsGeneratorHook.kt b/core/src/main/kotlin/eu/iamgio/quarkdown/context/hooks/TableOfContentsGeneratorHook.kt index a61af79d..b3f65e12 100644 --- a/core/src/main/kotlin/eu/iamgio/quarkdown/context/hooks/TableOfContentsGeneratorHook.kt +++ b/core/src/main/kotlin/eu/iamgio/quarkdown/context/hooks/TableOfContentsGeneratorHook.kt @@ -12,10 +12,7 @@ import eu.iamgio.quarkdown.context.toc.TableOfContents */ class TableOfContentsGeneratorHook(private val context: MutableContext) : AstIteratorHook { override fun attach(iterator: ObservableAstIterator) { - val headings = mutableListOf() - - // Collecting headings. - iterator.on { headings += it } + val headings = iterator.collectAll() // Generation. iterator.onFinished {