Skip to content

Commit

Permalink
Add highlightCode function
Browse files Browse the repository at this point in the history
FEATURE: The new `highlightCode` function provides a higher-level interface for
emitting highlighted code.
  • Loading branch information
marijnh committed Nov 12, 2023
1 parent 5d382e2 commit 308bca6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ on a Lezer syntax tree.

@tagHighlighter

@highlightCode

@highlightTree

@classHighlighter
33 changes: 32 additions & 1 deletion src/highlight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,9 @@ function highlightTags(highlighters: readonly Highlighter[], tags: readonly Tag[
}

/// Highlight the given [tree](#common.Tree) with the given
/// [highlighter](#highlight.Highlighter).
/// [highlighter](#highlight.Highlighter). Often, the higher-level
/// [`highlightCode`](#highlight.highlightCode) function is easier to
/// use.
export function highlightTree(
tree: Tree,
highlighter: Highlighter | readonly Highlighter[],
Expand All @@ -284,6 +286,35 @@ export function highlightTree(
builder.flush(to)
}

/// Highlight the given tree with the given highlighter, calling
/// `putText` for every piece of text, either with a set of classes or
/// with the empty string when unstyled, and `putBreak` for every line
/// break.
export function highlightCode(code: string, tree: Tree, highlighter: Highlighter | readonly Highlighter[],
putText: (code: string, classes: string) => void,
putBreak: () => void,
from = 0, to = code.length) {
let pos = from
function writeTo(p: number, classes: string) {
if (p <= pos) return
for (let text = code.slice(pos, p), i = 0;;) {
let nextBreak = text.indexOf("\n", i)
let upto = nextBreak < 0 ? text.length : nextBreak
if (upto > i) putText(text.slice(i, upto), classes)
if (nextBreak < 0) break
putBreak()
i = nextBreak + 1
}
pos = p
}

highlightTree(tree, highlighter, (from, to, classes) => {
writeTo(from, "")
writeTo(to, classes)
}, from, to)
writeTo(to, "")
}

class HighlightBuilder {
class = ""
constructor(
Expand Down

0 comments on commit 308bca6

Please sign in to comment.