codelight.js

Syntax highlighting that keeps up with live code.

Very fast and lightweight. Each line is highlighted once, and only the line being written gets updated, so it stays fast even when the code is long. No flicker, no dependencies.

0lines highlighted by codelight.js
0lines if every update re-highlighted the whole block
–less work, and finished lines never change

Use it

Code already on the page

Add two files and every <pre><code class="language-xxx"> block is highlighted. No build step. The code boxes on this page work this way.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/codelight.js/build/styles/default.min.css">
<script src="https://cdn.jsdelivr.net/npm/codelight.js/build/codelight.min.js"></script>
<script>codelight.highlightAll();</script>

Code that's streaming in

Mount a view once, then write each chunk as it arrives. Finished lines never change. The chat above works this way.

const view = codelight.mount(codeElement, { lang: "py" });

stream.on("data", (chunk) => view.write(chunk));

React

npm install codelight.js, then pass the whole reply on every update. Only the new part is highlighted.

import { CodeLight } from "codelight.js/react";
import "codelight.js/styles/default.css";

<CodeLight code={partialCode} lang="ts" />

Markdown replies

Find code blocks in a reply that's still streaming, including a fence that hasn't closed yet.

import { splitFences } from "codelight.js";

for (const part of splitFences(replySoFar)) {
  if (part.type === "code") views[i].set(part.code);
}

Languages

19 languages, all in the one 8 KB file. Pick one to see it highlighted.