Word Wrap

Wrap lines to avoid horizontal overflow.

content.md
```js
function lorem(ipsum, dolor, sit) {
ipsum.amet(
{ consectetur: [0, 1] },
{
adipiscing: elit.sed,
eiusmod: "lorem ipsum dolor sit amet",
sit,
},
)
}
```
1
function lorem(ipsum, dolor, sit) {
2
ipsum.amet(
3
{ consectetur: [0, 1] },
4
{
5
adipiscing: elit.sed,
6
eiusmod: "lorem ipsum dolor sit amet",
7
sit,
8
},
9
)
10
}
Drag the right handle to resize the width

Implementation

The easy way to make the code wrap is to style the <Pre /> component with white-space: pre-wrap;. But, when wrapping code, it's better to wrap the lines at the same indentation level. To do this, we can adjust the text-indent of each line:

word-wrap.tsx
import {
AnnotationHandler,
InnerLine,
InnerPre,
InnerToken,
} from "codehike/code"
export const wordWrap: AnnotationHandler = {
name: "word-wrap",
Pre: (props) => <InnerPre merge={props} className="whitespace-pre-wrap" />,
Line: (props) => (
<InnerLine merge={props}>
<div
style={{
textIndent: `${-props.indentation}ch`,
marginLeft: `${props.indentation}ch`,
}}
>
{props.children}
</div>
</InnerLine>
),
Token: (props) => <InnerToken merge={props} style={{ textIndent: 0 }} />,
}

Pass it to the handlers prop of the Pre component:

code.tsx
import { wordWrap } from "./word-wrap"
async function Code({ codeblock }: { codeblock: RawCode }) {
const highlighted = await highlight(codeblock, "github-dark")
return <Pre code={highlighted} handlers={[wordWrap]} />
}