Streaming Markdown: Auto-Close Incomplete LLM Output
A language model streams Markdown a few characters at a time, so most frames end inside a bold span, a code fence, or a component. autoCloseMarkdown() closes the syntax that is still open, so every frame renders as finished markup. parseMarkdown() and every renderer call it by default (the autoClose option), so you only call it yourself on raw Markdown strings.
autoCloseMarkdown(source, options?)
Closes unterminated Markdown syntax and Comark components in partial input. CommonMark and GFM healing follows the behavioral spec in packages/comark/SPEC/auto-close.md.
Parameters:
source- The Markdown content, which may be incompleteoptions(optional) - Feature flags and Comark settings:- Comark.
frontmatter: truecompletes an unclosed leading frontmatter block;syntax: falseskips component-fence closing;attributescontrols{...}attribute scopes (defaults tosyntax). - Links and images.
linkMode: 'protocol' | 'text-only'(default'protocol'),incompleteLinkPlaceholder(defaultcomark:incomplete-link), andincompleteImagePlaceholder(defaultcomark:incomplete-image). - Math. Inline
$...$and block$$...$$are off by default on bareautoCloseMarkdown. Passmath: true(or useparseMarkdownwith themathplugin). - Streaming.
dropTrailingOpeners: truedrops a trailing opener after whitespace (hello *→hello) so half-typed markers do not flash.parseMarkdown()enables this when called withstreaming: true.
- Comark.
Returns: string, the source with all unclosed syntax closed
Example:
import { autoCloseMarkdown } from 'comark'
autoCloseMarkdown('**bold text')
// '**bold text**'
autoCloseMarkdown('[partial link')
// '[partial link](comark:incomplete-link)'
autoCloseMarkdown('$x = 5')
// '$x = 5'
autoCloseMarkdown('$x = 5', { math: true })
// '$x = 5$'
autoCloseMarkdown('hello *', { dropTrailingOpeners: true })
// 'hello''**bold text**'parseMarkdown() and createMarkdownParser() run autoCloseMarkdown by default (autoClose: true).Parser integration
autoClose is enabled by default in parseMarkdown() and createMarkdownParser(). You can disable it or provide a custom completion function:
import { parseMarkdown } from 'comark'
const result = await parseMarkdown(content, {
autoClose: true // default
})import { parseMarkdown } from 'comark'
const result = await parseMarkdown(content, {
autoClose: false
})import { autoCloseMarkdown, parseMarkdown } from 'comark'
const closed = autoCloseMarkdown(content)
const result = await parseMarkdown(closed, { autoClose: false })import { createMarkdownParser } from 'comark'
const parse = createMarkdownParser({
autoClose: (markdown, streaming) => completeMarkdown(markdown, { streaming })
})During incremental parsing with { streaming: true }, the custom function receives only the unstable tail that Comark still needs to parse, and its second argument is true. On a regular parse, it receives the full input. The function must return the Markdown string to tokenize.
comark/auto-close instead of comark.Supported syntax
Inline Markdown
| Syntax | Example | Auto-closed |
|---|---|---|
| Bold | **text | **text** |
| Italic | *text / _text | *text* / _text_ |
| Bold-italic | ***text | ***text*** |
| Code | `code | `code` |
| Strikethrough | ~~text | ~~text~~ |
| Link (protocol) | [text](url | [text](comark:incomplete-link) |
| Link (text-only) | [text | text |
| Image |  |
| Block math | $$x | $$x$$ |
| Inline math | $x | $x$ (math: true) |
Comark components
Block components are closed based on their marker count:
// Double marker (block component)
autoCloseMarkdown('::alert\nContent')
// '::alert\nContent\n::'
// Triple marker (nested component)
autoCloseMarkdown(':::card\nContent')
// ':::card\nContent\n:::'
// Nested components
autoCloseMarkdown('::::outer\n:::inner\n::component')
// '::::outer\n:::inner\n::component\n::\n:::\n::::'Props and attributes
Components with props are handled correctly:
// Inline props
autoCloseMarkdown('::alert{type="info" title="Note"}')
// '::alert{type="info" title="Note"}\n::'
// YAML props
autoCloseMarkdown(`::component\n---\nkey: value\n---\nContent`)
// '::component\n---\nkey: value\n---\nContent\n::'Use cases
AI streaming
When streaming AI-generated Markdown, content arrives in chunks and may be incomplete at any point:
import { autoCloseMarkdown, parseMarkdown } from 'comark'
let accumulated = ''
socket.on('chunk', async (chunk) => {
accumulated += chunk
const closed = autoCloseMarkdown(accumulated)
const result = await parseMarkdown(closed)
renderContent(result.nodes)
})
socket.on('end', async () => {
const result = await parseMarkdown(accumulated)
renderFinalContent(result.nodes)
})AI SDK
The <Markdown> component runs autoCloseMarkdown on every render by default, so incomplete chunks render without broken syntax.
Install dependencies
npm install ai @ai-sdk/vueCreate a server route
import { convertToModelMessages, streamText } from 'ai'
export default defineEventHandler(async (event) => {
const { messages } = await readBody(event)
const result = streamText({
model: 'anthropic/claude-sonnet-4.6',
system: 'You are a helpful assistant. Always respond using Comark syntax.',
messages: await convertToModelMessages(messages),
})
return result.toUIMessageStreamResponse()
})Render on the client
Use the Chat class from @ai-sdk/vue and the <Markdown> component to parse and render the content as it arrives. Use isPartStreaming(part) for per-part streaming detection:
<script setup lang="ts">
import { Chat } from '@ai-sdk/vue'
import { isTextUIPart } from 'ai'
import { isPartStreaming } from '@nuxt/ui/utils/ai'
import { caret } from 'comark/stream'
const chat = new Chat({})
const input = ref('')
const effects = [caret()]
function onSubmit() {
chat.sendMessage({ text: input.value })
input.value = ''
}
</script>
<template>
<UChatMessages
should-auto-scroll
:messages="chat.messages"
:status="chat.status"
>
<template #indicator>
<UChatShimmer text="Thinking..." />
</template>
<template #content="{ message }">
<template
v-for="(part, index) in message.parts"
:key="`${message.id}-${part.type}-${index}`"
>
<template v-if="isTextUIPart(part)">
<p v-if="message.role === 'user'" class="whitespace-pre-wrap">
{{ part.text }}
</p>
<Suspense v-else>
<Markdown :value="part.text" :streaming="isPartStreaming(part)" :effects="effects" />
</Suspense>
</template>
</template>
</template>
</UChatMessages>
<UChatPrompt v-model="input" placeholder="Ask something..." @submit="onSubmit">
<UChatPromptSubmit
:status="chat.status"
@stop="chat.stop()"
@reload="chat.regenerate()"
/>
</UChatPrompt>
</template>The caret() effect from comark/stream, passed through the effects prop, appends a blinking cursor to the last text node while streaming. See stream effects for options and the Vue rendering docs for custom caret styling.
Real-time editor
Show a live preview while the user types:
import { autoCloseMarkdown, parseMarkdown } from 'comark'
import { renderHtmlFromDocument } from '@comark/html'
editor.addEventListener('input', async (e) => {
const closed = autoCloseMarkdown(e.target.value)
const result = await parseMarkdown(closed)
preview.innerHTML = await renderHtmlFromDocument(result)
})Incremental file upload
Parse content progressively as a file uploads:
import { autoCloseMarkdown, parseMarkdown } from 'comark'
async function uploadAndParse(file: File) {
const chunkSize = 64 * 1024 // 64KB
let offset = 0
let accumulated = ''
while (offset < file.size) {
const chunk = file.slice(offset, offset + chunkSize)
accumulated += await chunk.text()
const closed = autoCloseMarkdown(accumulated)
const result = await parseMarkdown(closed)
updateProgress({
percent: (offset / file.size) * 100,
preview: result.nodes
})
offset += chunkSize
}
return parseMarkdown(accumulated)
}Performance
Call autoCloseMarkdown once per chunk on the accumulated content, not on every character:
// Good: call once per chunk
for await (const chunk of stream) {
accumulated += chunk
const closed = autoCloseMarkdown(accumulated)
render(await parseMarkdown(closed))
}
// Avoid: calling for every character
for (const char of text) {
accumulated += char
const closed = autoCloseMarkdown(accumulated) // too frequent
render(await parseMarkdown(closed))
}