tree-sitter-ts-highlight
v0.1.4
Published
Syntax highlighting library built on tree-sitter-ts. HTML, ANSI, and decorations.
Maintainers
Readme
tree-sitter-ts-highlight
Fast syntax highlighting for Node and browser apps, built on tree-sitter-ts.
- HTML output (
<span>tokens or full<pre><code>block) - ANSI output for terminals/CLIs
- Side-by-side and inline diff highlighting
- Optional semantic token enhancement
- Built-in themes (CSS and JS theme objects)
Installation
npm install tree-sitter-ts-highlight tree-sitter-tstree-sitter-ts is a peer dependency and must be installed by your app.
Runtime requirements
- Node.js
>= 18 - ESM and CommonJS are both supported via package exports
Quick start
import { highlightBlock } from "tree-sitter-ts-highlight";
import "tree-sitter-ts-highlight/themes/github-dark.css";
const source = `export const answer = 42;`;
const html = highlightBlock(source, "typescript");
// html => <pre class="hlts hlts-lang-typescript"><code>...</code></pre>If you want only token spans (no wrapper):
import { highlight } from "tree-sitter-ts-highlight";
const innerHtml = highlight("const x = 1;", "typescript");
// => <span class="hlts-keyword">const</span> ...Core API
highlight(source, language, options?)
Returns syntax-highlighted HTML spans (no <pre><code> wrapper by default).
highlightBlock(source, language, options?)
Returns a full <pre><code> block. Equivalent to highlight(..., { wrapInPre: true }).
highlightAnsi(source, language, options?)
Returns ANSI-colored text for terminal output.
highlightDiff(oldSource, newSource, language, options?)
Returns highlighted diff HTML. Supports:
view: "side-by-side"(default)view: "inline"
diffModel(oldSource, newSource, options?)
Returns a framework-agnostic diff model (rows, line numbers, change types) for custom rendering.
highlightTokens(tokens, options?) / highlightTokensAnsi(tokens, options?)
Render pre-tokenized tree-sitter-ts tokens when tokenization is already done upstream.
enhanceSemantics(tokens)
Reclassifies overloaded identifier tokens (for richer semantic highlighting categories).
Common options
HTML options (HighlightOptions)
semanticHighlighting?: booleanlineNumbers?: booleanstartLine?: numberclassPrefix?: string(default prefix ishlts-)dataLineAttributes?: booleanwrapInPre?: booleandecorations?: Decoration[]theme?: HtmlTheme(inline style mode)language?: string(addshlts-lang-<language>class on<pre>)
ANSI options (AnsiHighlightOptions)
semanticHighlighting?: booleanlineNumbers?: booleanstartLine?: numberlineNumberWidth?: numbertheme?: AnsiTheme
Diff options (DiffOptions)
view?: "side-by-side" | "inline"semanticHighlighting?: booleanclassPrefix?: stringdecorations?: Decoration[]theme?: HtmlThemeoldLabel?: stringnewLabel?: stringshowHeader?: boolean
Theming
You can theme in two ways:
- CSS classes (recommended for app UI)
- Inline styles using exported theme objects
1) CSS theme import
import "tree-sitter-ts-highlight/themes/default-dark.css";Available CSS themes:
default-light.cssdefault-dark.cssgithub-light.cssgithub-dark.cssmonokai.cssdracula.cssnord.csssolarized-light.csssolarized-dark.csstokyo-night.csscatppuccin-mocha.css
2) Inline theme object
import { highlightBlock, githubDarkTheme } from "tree-sitter-ts-highlight";
const html = highlightBlock("const x = 1;", "typescript", {
theme: githubDarkTheme,
});Line numbers and data attributes
import { highlight } from "tree-sitter-ts-highlight";
const html = highlight("a\nb\nc", "typescript", {
lineNumbers: true,
startLine: 10,
dataLineAttributes: true,
});When line numbers are enabled, output uses a table layout with .hlts-table, .hlts-line-number, and .hlts-line-content.
Decorations
Use decorations to attach classes/styles/data attributes to source ranges.
import { highlight } from "tree-sitter-ts-highlight";
const source = "const value = 1;";
const html = highlight(source, "typescript", {
decorations: [
{
range: {
start: { line: 1, column: 6, offset: 6 },
end: { line: 1, column: 11, offset: 11 },
},
className: "my-marker",
data: { reason: "rename" },
priority: 1,
},
],
});Symbol fold arrows (optional)
Use decorateLineTableWithSymbolBlocks() to enrich line-number HTML with symbol fold toggles.
import {
highlight,
decorateLineTableWithSymbolBlocks,
} from "tree-sitter-ts-highlight";
import { extractSymbols } from "tree-sitter-ts";
const source = `function add(a, b) {\n return a + b;\n}`;
const symbols = extractSymbols(source, "typescript");
const htmlWithLines = highlight(source, "typescript", { lineNumbers: true });
const htmlWithBlocks = decorateLineTableWithSymbolBlocks(htmlWithLines, symbols, {
showFoldArrows: true,
});Fold arrows are shown only for symbols whose content spans multiple lines.
Terminal / CLI usage
import { highlightAnsi } from "tree-sitter-ts-highlight";
const colored = highlightAnsi("function foo() { return 42; }", "javascript", {
lineNumbers: true,
});
process.stdout.write(colored + "\n");Diff usage
import { highlightDiff } from "tree-sitter-ts-highlight";
import "tree-sitter-ts-highlight/themes/default-light.css";
const oldCode = "const x = 1;\nconsole.log(x);";
const newCode = "const x = 2;\nconsole.log(x);\nreturn x;";
const diffHtml = highlightDiff(oldCode, newCode, "typescript", {
view: "side-by-side",
oldLabel: "Before",
newLabel: "After",
});Built-in exports
Themes
defaultLightTheme,defaultDarkThemegithubLightTheme,githubDarkThememonokaiTheme,draculaTheme,nordThemesolarizedLightTheme,solarizedDarkThemetokyoNightTheme,catppuccinMochaThemedefaultAnsiThemebuiltinThemes,getTheme(name),getThemeNames()
Low-level utilities
renderTokensToHtml,renderTokensToAnsiwrapInLines,groupTokensByLinedecorateLineTableWithSymbolBlocksrenderDiffToHtmlcreateDiffModel,createDiffModelWithTokensapplyDecorations,splitTokensAtRangesescapeHtmlenhanceTokenSemantics
Re-exported tree-sitter-ts types
All exported types from tree-sitter-ts are re-exported from this package, so TypeScript users can import both highlighting APIs and tokenizer types from one module.
import type { Token, Range, TokenCategory } from "tree-sitter-ts-highlight";Language support
Language parsing/tokenization comes from tree-sitter-ts. Pass either language names (for example "typescript", "python") or extensions like ".ts".
Symbol range update (tree-sitter-ts >= 0.1.3-beta.2)
extractSymbols() now returns nameRange and contentRange on each symbol.
startLineandendLinewere removed upstream.nameRangepoints to the symbol name token span.contentRangepoints to the full symbol content span.
This enables richer editor features such as symbol-name highlighting and content collapse/expand behaviors.
Development
npm install
npm run typecheck
npm test
npm run buildDemo app:
npm run docs:serveLicense
MIT
