# Code Block (/docs/agent-ui/components/code-block)

Use a code block for a file, a command or a snippet the agent wrote. Markdown renders fenced code in one, and you can use it on its own. Name it with `aria-label`, like the file name.

<Example caption="Press the wrap button to wrap long lines, or the copy button to copy the code. Tab reaches both, and Enter or Space presses them.">
<h />

```tsx
import { CodeBlock } from "@/components/ui/code-block";

const code = `async function retry<T>(run: () => Promise<T>, tries = 4): Promise<T> {
  for (let attempt = 0; ; attempt++) {
    try {
      return await run();
    } catch (error) {
      if (attempt + 1 >= tries) throw error;
      await sleep(2 ** attempt * 250);
    }
  }
}`;

export default function CodeBlockExample() {
  return <CodeBlock aria-label="retry.ts" code={code} language="ts" lineNumbers />;
}
```
</Example>

## Installation [#installation]

```bash tab="React"
npx shadcn@latest add @kind-ui/code-block
```

```bash tab="Web Components"
npx shadcn@latest add @kind-ui/code-block-web
```

## Usage [#usage]

### Wrapping and Line Numbers [#wrapping-and-line-numbers]

Long lines scroll sideways until someone presses the wrap button, which reports its state with `aria-pressed`. Pass `defaultWrap` to start wrapped, or `wrap` with `onWrapChange` to control it. Pass `lineNumbers` to number each line.

### Copying [#copying]

The copy button copies the code and turns into a check for two seconds. It tells screen readers "Copied", or "Copy failed" when the browser refuses the clipboard write.

### Without the Header [#without-the-header]

Pass `header={false}` to leave out the language, the wrap button and the copy button, when the code sits under your own controls. On `<kind-code-block>`, add the `headerless` attribute instead.

### Highlighting [#highlighting]

No highlighter ships with it. Pass `highlight`, a function that resolves the code as a list of tokens whose contents, joined, are the code. Each token can have a `color`, any CSS color, and a `fontStyle` of `italic` or `bold`:

```tsx
import type { Highlight } from "@kind-ui/agent-ui/core";

const purple = "light-dark(#7c3aed, #c4b5fd)";

const highlight: Highlight = async (code) =>
  code.split(/(\bawait\b)/).map((content) => (content === "await" ? { content, color: purple } : { content }));
```

Plain text shows until the tokens arrive. A `light-dark()` color follows the page's color scheme. The block asks for one result at a time, and doesn't ask again for code that failed until the code or the language changes.

### Streaming [#streaming]

Set `streaming` while the code is still arriving, and the view follows its end. Highlighting keeps up: the start that's already colored stays colored, and the new lines show plain until the next result.

## API Reference [#api-reference]

### CodeBlockOptions

| Prop            | Type                                                                                        | Description                                                                                                                                                                                                                                         |
| --------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `code?`         | `string \| undefined`                                                                       | The code to show. Default: `""`                                                                                                                                                                                                                     |
| `language?`     | `string \| undefined`                                                                       | The code's language, like `"ts"`, shown in the header and passed to `highlight`.                                                                                                                                                                    |
| `highlight?`    | `Highlight \| undefined`                                                                    | Resolves colored tokens for the code; plain text shows until it does. While code streams in, the highlighted start shows with the rest plain. A new function each render is fine, and a rejection isn't retried until `code` or `language` changes. |
| `wrap?`         | `boolean \| undefined`                                                                      | Whether long lines wrap. Passing it controls it: change it in `onWrapChange`. Don't pass it with `defaultWrap`.                                                                                                                                     |
| `defaultWrap?`  | `boolean \| undefined`                                                                      | Whether long lines wrap at first, when `wrap` isn't passed. Default: `false`                                                                                                                                                                        |
| `onWrapChange?` | `((wrap: boolean, details: ChangeDetails<CodeBlockWrapChangeReason>) => void) \| undefined` | Called before wrapping turns on or off; cancel `details` to keep it as it is.                                                                                                                                                                       |
| `lineNumbers?`  | `boolean \| undefined`                                                                      | Numbers each line. Default: `false`                                                                                                                                                                                                                 |
| `streaming?`    | `boolean \| undefined`                                                                      | Whether the code is still arriving, so the view follows its end. Default: `false`                                                                                                                                                                   |

### Agent [#agent]

An agent connected with `createAgent` reads whether the code block wraps. It can run these actions, and press its buttons like a person would:

### CodeBlockAgentActions

| Prop         | Type                         | Description                                                                  |
| ------------ | ---------------------------- | ---------------------------------------------------------------------------- |
| `copy`       | `() => Promise<boolean>`     | Copies the code, and resolves with whether the clipboard write went through. |
| `toggleWrap` | `(event?: Event) => boolean` | Turns line wrapping on or off, and returns whether the change was accepted.  |

<Caption>
Runs in React and Web Components. On `<kind-code-block>`, each prop is a kebab-case attribute, so `lineNumbers` is `line-numbers`, and `onWrapChange` fires `wrapchange`. Set `highlight` as a property.
</Caption>