# Markdown Preview Fold: Folding Sections in the VS Code Markdown Preview
I read a lot of Markdown in my editor: specs, READMEs, my own notes. In Obsidian I fold the sections I’ve already read and keep open only the part I’m working on. The Markdown preview in VS Code and Cursor can’t do that, so a long document stays one long scroll.
I wrote my first VS Code extension to fix it. Markdown Preview Fold puts a caret next to every heading in the built-in preview, and a click folds the section. I released 0.1.0 on November 25, 2026, and it’s at 0.1.3 now.
What it does
- A caret appears on hover next to every heading that has something under it, and stays visible while the section is folded. A folded heading gets a ”…” after its text.
- Subsections keep their own state. Fold “Install”, then fold and unfold “Setup” above it, and “Install” is still folded.
- The state survives edits, tab switches and editor restarts, separately for each file.
- Collapse All and Expand All are in the preview’s title bar, in the Command Palette, and on
Cmd+K Cmd+0/Cmd+K Cmd+J(Ctrlon Windows and Linux). They only apply while the preview has focus, so in the text editor the same keys still fold code. - Option+click (Alt+click on Windows and Linux) folds a section together with all its subsections.
- A link to a heading inside a folded section opens the sections above it.
The caret is a real <button>, so it works with the keyboard and screen readers. Colors come from your theme, high contrast themes included.
Why I didn’t use an existing extension
Markdown Preview Enhanced and similar extensions replace the preview with their own. I wanted one feature added to the preview I already use, with its scroll sync, styles and settings.
Cursor was the other question. It has its own WYSIWYG Markdown editor, but that editor lives in Cursor’s workbench code, and extensions have no API to reach it. The built-in VS Code preview does accept scripts, styles and markdown-it plugins from other extensions. If I target that preview, one extension works in VS Code, Cursor, VSCodium and Windsurf. In Cursor you open it with “Markdown: Open Preview to the Side”.
Two runtimes that can’t call each other
The extension plugs into the built-in Markdown extension through three contribution points:
"contributes": { "markdown.markdownItPlugins": true, "markdown.previewScripts": ["./dist/preview.js"], "markdown.previewStyles": ["./media/preview.css"]}That code runs in two places. The extension host is a Node process with the vscode API: commands, menus, key bindings. It sees the Markdown engine but not the preview page. The preview page is a browser page inside a webview, with the DOM and localStorage. It can’t import vscode, and the built-in preview already holds the only acquireVsCodeApi() handle, so the page can’t message my extension either.
The build keeps them apart with two esbuild bundles and two tsconfig projects: Node and vscode types without the DOM, and the DOM without vscode. Code in the wrong runtime doesn’t compile.
The preview rewrites its DOM on every edit
This was my first surprise. The preview never reloads when you type. It renders new HTML in the extension host, posts it to the page and patches .markdown-body with morphdom. Morphdom compares the DOM with the new HTML, and my classes and carets aren’t in that HTML, so after each keystroke they were gone.
The script keeps the fold state in memory, and renderView is idempotent: run it any number of times on the same DOM and you get the same result. It runs on every vscode.markdown.updateContent event, which the preview fires after each patch. The patch and my render happen in the same task, before the browser paints, so there’s no flicker.
export function renderView(view: PreviewView, collapsed: ReadonlySet<string>): void { view.elements.forEach((element, index) => { setHidden(element, isHiddenBy(view.outline.owners[index], collapsed)); }); for (const section of view.outline.sections) { const heading = view.elements[section.blockIndex]; if (heading) renderHeading(heading, section, collapsed.has(section.key)); }}To survive edits, a section needs a key that doesn’t depend on its position. Line numbers change with every edit, and the preview’s heading ids are slugs with numeric suffixes that shift across the document. So a key comes from the heading path: the parent’s key, the heading text, and the index of that text among its siblings, for example Guide#0 › Setup#0. Editing content keeps every key. Renaming a heading resets that section, and the README lists it as a known limitation.
There was one more case. When the page loads from scratch (you open the preview or switch back to its tab), the preview’s own script adds .markdown-body after DOMContentLoaded and fires no update event. Both scripts load with async, so either can run first. I noticed it in Cursor: after a tab switch, the carets didn’t show up until the next edit. Now a MutationObserver waits for .markdown-body and disconnects on the first update.
Talking to a page you don’t own
Collapse All is a VS Code command, so it runs in the extension host, which has no channel to the page. The only thing the host can get onto the page is the HTML it helps render.
So a markdown-it plugin adds a hidden marker to every render with the document URI and the pending command. The hard part was finding where to hook in. The engine caches parsed tokens per document version and passes env.currentDocument only to renderer.render. A core rule would see neither the document nor a new command. I found that by reading the built-in extension’s code, and the plugin wraps renderer.render:
export function markerPlugin(md: MarkdownIt, options: MarkerOptions): void { const render = md.renderer.render.bind(md.renderer); md.renderer.render = (tokens, renderOptions, env: RenderEnv | undefined) => { const html = render(tokens, renderOptions, env); const doc = env?.currentDocument; if (!doc) return html; return markerHtml(md, doc.toString(), options.getCommand()) + html; };}When you run Collapse All, the command stores collapseAll:<uuid> for 1.5 seconds and calls markdown.preview.refresh. The refresh is forced, so the preview sets the webview’s HTML again, the page reloads, and the marker in the new HTML carries the command. The script applies each command id once.
My first version got this wrong. It ignored a command on a page’s first update, because I assumed the refresh would post updateContent to the existing page. It reloads the page instead, so every bulk command was dropped. I found out by reading the markdown-language-features extension bundled with Cursor.
The host can’t tell which preview has focus, so Collapse All and Expand All act on every open preview.
State that survives restarts
The webview setState API belongs to the built-in preview, so it wasn’t available to me. Then I learned that the workbench gives each webview type a stable origin, so the preview’s localStorage persists across tab switches and restarts. The extension keeps one versioned entry, keyed by file URI, with the 200 most recently changed files. Every access is wrapped in try/catch, so in a sandbox without storage folding still works for the session.
Testing and shipping
There are 65 unit and DOM tests in Vitest for the outline, keys, reducer and DOM code. Some of them run the whole script against a stand-in preview that updates with real morphdom. Four integration tests run in a real VS Code through @vscode/test-cli. CI runs on Linux, macOS and Windows against VS Code 1.90 and stable.
The .vsix is around 16 KB, and preview.js is 5.6 KB minified. A git tag publishes to Open VSX and GitHub Releases.
I wanted the Marketplace in the same workflow, with Trusted Publishing (OIDC) and no stored token. The token exchange returned 401. GitHub repositories created after 2026-07-15 get immutable subject claims, and the most likely cause is that the Marketplace doesn’t match that format yet. A personal access token would need an Azure DevOps organization, and a new one needs an Azure subscription. For now I upload the same CI-built .vsix to the Marketplace by hand. ADR 010 in docs/decisions.md has the details.
Install
Install it from the Extensions view or the links below, then open a Markdown file and run Markdown: Open Preview to the Side (Cmd+K V on macOS, Ctrl+K V on Windows and Linux).
The extension has no telemetry, makes no network requests, and never touches your files. It’s MIT licensed.
- VS Code Marketplace
- Open VSX, for Cursor, VSCodium and Windsurf
- Source code on GitHub, with how it works and why it works this way
If you find a bug or have an idea, open an issue.