Word Wrap

How to enable word wrap in code blocks using Shiki.

ShikiMarkdownMDX

Installation

shadcn/ui

shadcn/ui Command
pnpm dlx shadcn@latest add https://code-blocks.pheralb.dev/r/shiki-word-wrap.json

Manual

  1. Copy the wordWrapContent transformer into your project:
.ts
import type { ShikiTransformer } from "shiki";

const wordWrapContent = (): ShikiTransformer => {
  return {
    name: "WordWrap",
    pre(node) {
      const existingClass = node.properties.class;
      if (Array.isArray(existingClass)) {
        existingClass.push("shiki-word-wrap");
      } else if (typeof existingClass === "string") {
        node.properties.class = `${existingClass} shiki-word-wrap`;
      } else {
        node.properties.class = "shiki-word-wrap";
      }
    },
  };
};

export { wordWrapContent };

shiki-word-wrap styles are defined in the shiki.css file:

shikiShiki Highlighter#styles

The main highlighter utility to render syntax highlighted code.

  1. Import the transformer in your rehypeShiki plugin:
Rehype Shiki Options
import { wordWrapContent } from "@/utils/shiki/transformers/word-wrap";

const rehypeShikiOptions: RehypeShikiCoreOptions = {
  //...
  transformers: [wordWrapContent()],
};

export { rehypeShikiOptions };

Then, automatically long lines in your code blocks will wrap based on the width of the container.