Highlighting
Highlight code in pure Dart and read the result — flat tokens with scope stacks, lines, and the questions an editor asks.
val_highlight has no Flutter dependency: the same calls work in a Flutter
app, on a server, in a command-line tool and on the web.
import 'package:val_highlight/val_highlight.dart';import 'package:val_highlight/languages/dart.dart';
final result = const Highlighter().highlight(source, language: dartLanguage);A Highlighter holds no mutable state, so one instance can be shared, from
any isolate. Each language is compiled the first time it is used, and the
compiled form is kept for the life of the grammar.
Tokens
Section titled “Tokens”A HighlightResult splits the source into tokens that cover all of it, with
no gaps. Each token carries a scope stack, from the outermost scope in:
const source = r"var s = 'Hi ${name.length}!';";final result = const Highlighter().highlight(source, language: dartLanguage);
for (final token in result.tokens) { print('${token.scopes.join(' > ')}: "${token.text}"');}keyword: "var": " s "operator: "=": " "string: "'Hi "string > interpolation: "${name.length}"string: "!'": ";"Plain text has an empty stack. Neighbouring tokens never share a stack, so a
token is a whole run of text with the same scopes: one string, one comment,
one keyword. The standard scopes are constants on
Scopes.
Tokens are stored flat, as two integer lists, rather than as objects:
result.tokens builds a light HighlightToken view on demand. For speed,
read them by index — tokenCount, tokenStart(i), tokenEnd(i) and
tokenStack(i) — and resolve a stack’s scopes through result.scopes, a
ScopeTable. tokenAt(offset) finds the token covering an offset.
Renderers usually work a line at a time:
for (var line = 0; line < result.lineCount; line++) { result.forEachSegment(line, (start, end, stack) { final scope = result.scopes.scopeOf(stack); // null for plain text // draw source.substring(start, end) in the style for this stack });}forEachSegment calls back with the pieces of one line, cut where a token
crosses the line break, and never includes the break itself. lineStart and
lineEnd give a line’s offsets; lineEnd excludes the \n or \r\n. Empty
source has one empty line, and a trailing \n starts a final empty line.
Questions an editor asks
Section titled “Questions an editor asks”The result answers them from the tokens, so a bracket or a quote inside a string or comment is never mistaken for code:
final result = const Highlighter().highlight( 'f(")") + g[1]', language: dartLanguage,);
result.matchingBracket(1); // 5 — the ")" inside the string is skippedresult.matchingBracket(10); // 12result.isStringOrCommentAt(3); // true — the character at offset 3result.isInsideStringOrComment(3); // true — text typed between offsets 2 and 3result.isInsideStringOrComment(5); // false — right after the closing quotematchingBracket returns -1 when the character is not a bracket in code,
or has no match within limit characters. Interpolations inside strings
count as code. CodeField uses these for bracket marks and for deciding when
a quote should close itself.
By name
Section titled “By name”To highlight by a language’s name or alias, give the highlighter a registry:
final highlighter = Highlighter(registry: allLanguagesRegistry());final result = highlighter.highlightByName('a: 1', name: 'yml'); // YAMLIt throws UnknownLanguageException when there is no registry, or the name
is unknown and the registry has no fallback. A registry also lets Markdown
highlight its fenced code; see
lookup and detection.
Results across isolates
Section titled “Results across isolates”HighlightResult.fromBuffers rebuilds a result from its raw lists
(rawEnds, rawStacks), for code that moves results between isolates.
CodeHighlighter in val_highlight_flutter already highlights large inputs
in a background isolate.
API reference
Section titled “API reference”Highlighter
Section titled “Highlighter”Highlights source code.
final result = const Highlighter().highlight(code, language: dartLanguage);print(result.toHtml());A highlighter holds no mutable state, so one instance can be shared, and it is safe to use from any isolate.
const Highlighter({ LanguageRegistry? registry,})Creates a highlighter.
registry enables lookup by name and resolves languages named inside
the code, such as Markdown code fences.
| Field | Type | Description |
|---|---|---|
registry |
LanguageRegistry? |
Languages available by name, if any. |
| Member | Type | Description |
|---|---|---|
highlight(String code, {required Grammar language}) |
HighlightResult |
Highlights code with language. |
highlightByName(String code, {required String name}) |
HighlightResult |
Highlights code with the language registered as name or an alias, or the registry’s fallback. |
toHtml(…) |
String |
Highlights code with language and renders it as HTML. |
highlightByName: more
Throws UnknownLanguageException if there is no such language and no
fallback.
HighlightResult
Section titled “HighlightResult”The output of highlighting: code split into contiguous tokens.
Tokens are stored flat, as two parallel integer lists, rather than as a
tree of objects. Token i covers code[tokenStart(i), tokenEnd(i)) and
carries a scope stack id from scopes. Tokens always cover all of code
with no gaps, and neighbouring tokens never share a stack.
| Field | Type | Description |
|---|---|---|
code |
String |
The highlighted source. |
language |
Grammar |
Grammar used to highlight code. |
scopes |
ScopeTable |
Scope names and stacks referenced by the tokens. |
tokenCount |
int |
Number of tokens. |
| Member | Type | Description |
|---|---|---|
HighlightResult.fromBuffers({…}) |
HighlightResult |
Creates a result from raw token buffers. |
tokenStart(int index) |
int |
Start offset of token index. |
tokenEnd(int index) |
int |
End offset (exclusive) of token index. |
tokenStack(int index) |
int |
Scope stack id of token index. See scopes. |
rawEnds |
Int32List |
The raw token end offsets, for engines that copy tokens in bulk. Only the first tokenCount entries are valid. |
rawStacks |
Int32List |
The raw token stack ids, alongside rawEnds. |
tokens |
Iterable<HighlightToken> |
All tokens, in order. |
tokenAt(int offset) |
int |
Index of the token covering offset, or tokenCount if offset is at or past the end. |
lineCount |
int |
Number of lines. Empty code has one empty line, and a trailing \n starts a final empty line. |
lineStart(int line) |
int |
Start offset of line line. |
lineEnd(int line) |
int |
End offset of line line, excluding its \n or \r\n. |
forEachSegment(…) |
void |
Calls segment for each piece of line line, in order, with the piece’s offsets and scope stack. Pieces never include the line break. |
isStringOrCommentAt(int offset) |
bool |
Whether the character at offset is inside a string, comment or regular expression. Interpolations inside strings count as code. |
isCommentAt(int offset) |
bool |
Whether the character at offset is inside a comment. |
isInsideStringOrComment(int offset, [EditingSyntax? syntax]) |
bool |
Whether text typed at caret position offset, between code[offset - 1] and code[offset], would land inside a string or comment. |
matchingBracket(…) |
int |
Offset of the bracket matching the one at offset, or -1 if the character at offset is not a bracket in code, or has no match within limit characters. |
toHtml([HtmlRenderer renderer = const HtmlRenderer()]) |
String |
Renders the result as HTML. See HtmlRenderer for options. |
HighlightResult.fromBuffers: more
Engines use this, and so can code that moves results between isolates.
ends and stacks must have at least tokenCount entries. Pass
lineStarts if they are already known.
isInsideStringOrComment: more
Unlike isStringOrCommentAt, this answers for a position between
characters: right after a closing quote is outside the string, while
the end of a line comment or of an unterminated string is inside.
syntax supplies the block comment marker; it defaults to
EditingSyntax.of the language.
matchingBracket: more
brackets lists pairs as consecutive opening and closing characters,
as in EditingSyntax.brackets. Brackets inside strings and comments
are skipped, so f(")") matches correctly. The search walks tokens,
jumping over a whole string or comment at once.
HighlightToken
Section titled “HighlightToken”A lightweight view of one token in a HighlightResult.
| Field | Type | Description |
|---|---|---|
index |
int |
Position of this token in the result. |
| Member | Type | Description |
|---|---|---|
start |
int |
Start offset in the source. |
end |
int |
End offset (exclusive) in the source. |
stack |
int |
Scope stack id. |
text |
String |
Source text covered by this token. |
scope |
String? |
Innermost scope, or null for plain text. |
scopes |
List<String> |
Scopes from the outermost to the innermost. |
ScopeTable
Section titled “ScopeTable”Interned scope names and scope stacks for one highlight result.
Every token records a single stack id. A stack is a chain of scopes from
the outside in, such as string > interpolation > keyword. Stack 0 is
the root and has no scope. A parent always has a smaller id than its
children, so renderers can resolve styles in a single forward pass.
ScopeTable()Creates an empty table containing only the root stack.
| Member | Type | Description |
|---|---|---|
static root |
int |
Id of the root stack, which has no scope. |
stackCount |
int |
Number of stacks, including the root. |
nameId(String name) |
int |
Returns the id of scope name, adding it if needed. |
push(int stack, String name) |
int |
Returns the stack made of stack with scope name pushed on top. |
parentOf(int stack) |
int |
Parent of stack, or -1 for the root. |
scopeOf(int stack) |
String? |
Innermost scope of stack, or null for the root. |
scopesOf(int stack) |
List<String> |
Scopes of stack from the outermost to the innermost. |
pathOf(int stack) |
List<int> |
Stack ids from the outermost to stack, excluding the root. |
isStringOrComment(int stack) |
bool |
Whether stack is inside a string, comment or regular expression. |
isComment(int stack) |
bool |
Whether stack is inside a comment. |
isStringOrComment: more
An interpolation inside a string, such as ${x}, is code again: its
stacks are not.