Code Blocks

Fenced code in every supported language, plus filenames, line numbers, line highlights, character highlights, and diffs.

5 min readshowcasereferencecode

The code renderer is built on Shiki via rehype-pretty-code. It supports per-language syntax highlighting, filenames, line numbers, highlighted lines, highlighted characters, and unified diff output.

Inline code

Inline code spans render with monospace styling and a subtle background. They're for short identifiers, not full statements. If you find yourself wrapping more than a few words, reach for a fenced block instead.

Languages

A small tour of the languages worth knowing the syntax for.

TypeScript

type Result<T> =
  | { ok: true; value: T }
  | { ok: false; error: string };
 
export function divide(a: number, b: number): Result<number> {
  if (b === 0) return { ok: false, error: "divide by zero" };
  return { ok: true, value: a / b };
}

JavaScript

const fib = (n) =>
  n < 2 ? n : fib(n - 1) + fib(n - 2);
 
console.log(fib(10));

Python

def fizzbuzz(n: int) -> list[str]:
    out = []
    for i in range(1, n + 1):
        if i % 15 == 0:
            out.append("FizzBuzz")
        elif i % 3 == 0:
            out.append("Fizz")
        elif i % 5 == 0:
            out.append("Buzz")
        else:
            out.append(str(i))
    return out

Go

package main
 
import "fmt"
 
func main() {
    nums := []int{1, 1, 2, 3, 5, 8, 13}
    sum := 0
    for _, n := range nums {
        sum += n
    }
    fmt.Println("sum:", sum)
}

Rust

fn main() {
    let words = vec!["alpha", "bravo", "charlie"];
    let joined: String = words.join(", ");
    println!("{}", joined);
}

JSON

{
  "name": "brad",
  "version": "1.4.0",
  "modules": ["clients", "sales", "tickets"],
  "active": true
}

SQL

SELECT c.id, c.email, COUNT(t.id) AS open_tickets
FROM clients c
LEFT JOIN tickets t ON t.client_id = c.id AND t.status = 'open'
GROUP BY c.id, c.email
ORDER BY open_tickets DESC
LIMIT 10;

HTML

<article class="card">
  <header>
    <h2>Welcome</h2>
  </header>
  <p>A simple card with a header and body.</p>
</article>

CSS

.card {
  border-radius: 0.75rem;
  padding: 1.5rem;
  background: hsl(220 14% 12%);
  color: hsl(0 0% 96%);
}

Bash

#!/usr/bin/env bash
set -euo pipefail
 
for file in *.md; do
  wc -w "$file"
done

Plaintext

Some content with no syntax highlighting at all.
Useful for log output, ASCII tables, or anything
that isn't really a language.

Filenames

Add title="..." to the fence to render a filename header above the block.

export function formatCurrency(cents: number, currency = "USD"): string {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency,
  }).format(cents / 100);
}

Line numbers

Add showLineNumbers to render a gutter with line numbers — handy when you want to reference a specific line in prose.

import { z } from "zod";
 
const ClientSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  name: z.string().min(1),
  isAdmin: z.boolean().default(false),
});
 
export type Client = z.infer<typeof ClientSchema>;

Highlighted lines

Use {N} or {N-M} to highlight specific lines. Combine with showLineNumbers when you want both.

import { getIronSession } from "iron-session";
import { cookies } from "next/headers";
import type { SessionData } from "./types";
 
export async function getSession(): Promise<SessionData | null> {
  const session = await getIronSession<SessionData>(await cookies(), {
    password: process.env.APP_KEY!,
    cookieName: "brad_session",
  });
  return session.clientId ? session : null;
}

The highlighted lines mark the import that matters and the iron-session call that does the work.

Highlighted characters

Wrap a substring in slashes to highlight every occurrence of it within the block. Useful when the point of the example is a single function or token.

import { useAuthStore } from "@/lib/store";
 
export function Greeting() {
  const client = useAuthStore((s) => s.client);
  if (!client) return null;
  return <span>Hi, {client.name}</span>;
}

You can also scope a highlight to a specific line range with a #N-M suffix — /term/#2-4 only highlights matches on lines 2-4.

Diffs

Use the diff language for unified diff output. Lines starting with + are additions, - are removals, and unchanged lines render as context.

 export function greet(name: string): string {
-  return "Hello, " + name;
+  return `Hello, ${name}!`;
 }
 
-const greeting = greet("World");
+const greeting = greet("Friend");
 console.log(greeting);

For longer changes, prefer linking to a real commit or PR over pasting a diff. Diff blocks are best for tutorials where you want to focus the reader's eye on what changed.

Share this page

Code Blocks

Fenced code in every supported language, plus filenames, line numbers, line highlights, character highlights, and diffs.

/docs/showcase/code-blocks
Xin