Is it possible to only show the headings of the embeded markdown file?

I’m writing a book. I want to have a living index file in which all headings in all chapter files are embeded.

I used the syntax like this ![[ chapter1.md]] ,![[ chapter2.md]]![[chatper9.md]]. However, all levels of text were displayed in reading mode. I wonder if there is a way to just show the headings (maybe from level 1 to level 4) of the chatper files. Therefore, I can get a living index of the Book in case the headings in chapter files are changed.

You could modify the dynamic table-of-contents script from here:

It will automatically give you links to all headings, which will let you click through to the section itself. Just do one of these for each .md file.

Thank you for your suggestion. It works only for a single file. However, I need to combine all the headings of many chapter files in one index file.

Yes, so like I said in my post - just do one for each file inside the single index page. Either multiple datablocks or update a single codeblock to point at multiple files like this:

```dataviewjs
const A_BUNCH_OF_FILES = ['File1.md', 'File2.md']

for (const eachFile of A_BUNCH_OF_FILES) {
  const page = dv.page(eachFile)
  if (!page) continue
  const startAtLevel = 2
  const content = await dv.io.load(page.file.path)
  const toc = content.match(new RegExp(`^#{${startAtLevel},} \\S.*`, 'mg'))
    .map(heading => {
      const [_, level, text] = heading.match(/^(#+) (.+)$/)
      const link = dv.current().file.path + '#' + text
      return '\t'.repeat(level.length - startAtLevel) + `1. [[${link}|${text}]]`
    })
  dv.header(2, 'Table of contents for ' + page.file.name)
  dv.paragraph(toc.join('\n'))
}
```
1 Like

Thank you. Another follow-up question. How to handle the path of ‘File1.md’ if it is not under the root path of my Obsidian vault? I tried a relative path (for example ‘./05-Writing/01-Coding/01-SAScoding/03-mdv/File1.md’ ), but it seems that it doesn’t work.

It doesn’t need to be in the root the way I wrote it - Dataview will find it with just the name of the note without path. It’s the same format you’d use in a normal internal link.

However rather than using the A_BUNCH_OF_FILES array the way I put it in the example code, you’d probably be better to just use a dv.pages query there to fetch all the chapter files in one go.

Thank you. I have no idea how to use dv.pages. I drop the “./” in the path, it works well now.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.