<!-- Source: https://markdown.svelte.page/examples/code-formatting -->

# Code Formatting

> Format code blocks in @humanspeak/svelte-markdown with an async marked-code-format walkTokens extension or an inline Svelte 5 code snippet override.

**Source:** [https://markdown.svelte.page/examples/code-formatting](https://markdown.svelte.page/examples/code-formatting)

**Markdown mirror:** [https://markdown.svelte.page/examples/code-formatting.md](https://markdown.svelte.page/examples/code-formatting.md)

---

This mirror preserves the prose, implementation notes, and runnable Svelte source behind the live example page.

## FIG-001: prettier walktokens.

Add `prettier` to any code fence and the `marked-code-format` extension auto-formats it through Prettier — async walkTokens callback, no custom renderer needed.

**Metadata:** tag: `EXTENSION` | technique: `extension`

### Notes

- `marked-code-format` registers an async `walkTokens` callback that runs Prettier on every code fence with the `prettier` info-string marker.
- Prettier loads lazily — only when a fence opts in. No bundle cost when you're not using it.
- Best when you ingest raw, unformatted code (e.g. agent output) and want consistent code-block presentation.

### Source

#### PrettierExtension.svelte

Source file: [src/lib/examples/code-formatting/demos/PrettierExtension.svelte](https://github.com/humanspeak/svelte-markdown/blob/main/docs/src/lib/examples/code-formatting/demos/PrettierExtension.svelte)

```svelte
<script lang="ts">
    import SvelteMarkdown from '@humanspeak/svelte-markdown'
    import type { MarkedExtension } from 'marked'
    import { onMount } from 'svelte'
    import { LoaderCircle } from '@lucide/svelte'

    const markdown = `## Code Formatting with marked-code-format

Auto-format code blocks with [Prettier](https://prettier.io/) by adding the \`prettier\` attribute to your code fences.

### JavaScript

\`\`\`js prettier
function   fibonacci(n){if(n<=1)return n
return fibonacci(n-1)+fibonacci(n-2)}

const   result=fibonacci(10)
console.log(result)
\`\`\`

### CSS

\`\`\`css prettier
.container{display:flex;justify-content:center;align-items:center;gap:1rem}
.card{border-radius:0.5rem;padding:1rem;box-shadow:0 1px 3px rgba(0,0,0,0.12)}
\`\`\`

### TypeScript

\`\`\`ts prettier
interface User{name:string;age:number;email?:string}
const greet=(user:User):string=>\`Hello, \${user.name}! You are \${user.age} years old.\`
\`\`\`

### Unformatted (no prettier attribute)

\`\`\`js
const x={a:1,b:2,c:3}
\`\`\`

> **Tip:** Only code fences with the \`prettier\` attribute are formatted. Others are left as-is.`

    // marked-code-format and prettier are heavy and not bundled by default
    // — lazy-load them on mount so the rest of the page paints first. The
    // `async: true` flag in the extension makes SvelteMarkdown await the
    // walkTokens transformation before rendering each token.
    let extensions = $state<MarkedExtension[]>([])
    let ready = $state(false)

    onMount(async () => {
        const [
            { default: markedCodeFormat },
            { default: prettierPluginBabel },
            { default: prettierPluginEstree },
            { default: prettierPluginCss },
            { default: prettierPluginTypescript }
        ] = await Promise.all([
            import('marked-code-format'),
            import('prettier/plugins/babel'),
            import('prettier/plugins/estree'),
            import('prettier/plugins/postcss'),
            import('prettier/plugins/typescript')
        ])

        extensions = [
            markedCodeFormat({
                plugins: [
                    prettierPluginBabel,
                    prettierPluginEstree,
                    prettierPluginCss,
                    prettierPluginTypescript
                ]
            })
        ]
        ready = true
    })
</script>

<!--
  Code formatting via the `marked-code-format` extension. Code fences
  tagged with `prettier` get auto-formatted by Prettier through the
  extension's async `walkTokens` callback — no custom renderer needed.
-->
<div class="prose prose-sm dark:prose-invert mx-auto max-w-4xl px-6 py-6">
    {#if ready}
        <SvelteMarkdown source={markdown} {extensions} />
    {:else}
        <div class="cf-loading">
            <LoaderCircle class="size-4 animate-spin" />
            Loading formatter…
        </div>
    {/if}
</div>

<style>
    .cf-loading {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 2rem 0;
        font-size: 0.875rem;
        color: var(--brut-ink-3, currentColor);
    }
</style>
```

## FIG-002: snippet override.

Use an inline `{#snippet code}` to control the code block markup — language badge in the corner, brut chrome around the body. Receives `{ lang, text }` props.

**Metadata:** tag: `SNIPPET` | technique: `inline snippet`

### Notes

- `{#snippet code({ lang, text })}` receives the parsed language + body. Wrap it in any chrome you want — language badge, copy button, line numbers.
- Pairs nicely with the extension above: format with `marked-code-format`, then present with the snippet.

### Source

#### SnippetRendered.svelte

Source file: [src/lib/examples/code-formatting/demos/SnippetRendered.svelte](https://github.com/humanspeak/svelte-markdown/blob/main/docs/src/lib/examples/code-formatting/demos/SnippetRendered.svelte)

```svelte
<script lang="ts">
    import SvelteMarkdown from '@humanspeak/svelte-markdown'

    const markdown = `## Code Block Styling

Customize code block rendering without an extension — just an inline \`{#snippet code}\` block.

### JavaScript

\`\`\`js
function fibonacci(n) {
    if (n <= 1) return n
    return fibonacci(n - 1) + fibonacci(n - 2)
}

const result = fibonacci(10)
console.log(result)
\`\`\`

### CSS

\`\`\`css
.container {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 1rem;
}
\`\`\`

### TypeScript

\`\`\`ts
interface User {
    name: string
    age: number
    email?: string
}

const greet = (user: User): string =>
    \`Hello, \${user.name}! You are \${user.age} years old.\`
\`\`\`

### Bash

\`\`\`bash
pnpm add @humanspeak/svelte-markdown
\`\`\`

> **Tip:** The snippet gets \`{ lang, text }\` so the language label can drive per-language styling.`
</script>

<!--
  Snippet override for the `code` token — wraps each fenced code block
  in a brut-themed container with a language badge in the corner. No
  extension required, full markup control per page.
-->
<div class="prose prose-sm dark:prose-invert mx-auto max-w-4xl px-6 py-6">
    <SvelteMarkdown source={markdown}>
        {#snippet code(props: { lang: string; text: string })}
            <div class="cf-block">
                {#if props.lang}
                    <div class="cf-lang">{props.lang}</div>
                {/if}
                <pre><code>{props.text}</code></pre>
            </div>
        {/snippet}
    </SvelteMarkdown>
</div>

<style>
    /* Container + lang badge use brut tokens so the chrome flips
       between light and dark themes. The pre is left on the brut bg
       surface with mono typography — no syntax highlighting (the
       snippet API doesn't provide tokenised output; the extension
       variant handles formatting separately). */
    :global(.cf-block) {
        position: relative;
        margin: 14px 0;
        border: 1px solid var(--brut-rule);
        background: var(--brut-bg-2);
    }
    :global(.cf-lang) {
        display: inline-block;
        padding: 4px 10px;
        background: var(--brut-accent);
        color: var(--brut-accent-ink);
        font-family: 'JetBrains Mono Variable', 'JetBrains Mono', ui-monospace, monospace;
        font-size: 10.5px;
        letter-spacing: 0.14em;
        text-transform: uppercase;
        font-weight: 600;
    }
    :global(.cf-block pre) {
        margin: 0;
        padding: 14px 16px;
        background: transparent;
        color: var(--brut-ink);
        font-family: 'JetBrains Mono Variable', 'JetBrains Mono', ui-monospace, monospace;
        font-size: 12.5px;
        line-height: 1.65;
        overflow-x: auto;
    }
    :global(.cf-block code) {
        background: transparent;
        color: inherit;
        padding: 0;
        border: 0;
    }
</style>
```
