syntax library

TextMate-grammar syntax highlighting in pure Dart.

import 'package:syntax_darts/syntax.dart';
import 'package:syntax_darts/langs/dart.dart';
import 'package:syntax_darts/themes/github_dark.dart';

final highlighter = Highlighter(languages: [dartLanguage]);
print(highlighter.toAnsi(code, language: 'dart', theme: githubDarkTheme));

Bundled grammars live under package:syntax_darts/langs/ and themes under package:syntax_darts/themes/. Import only the ones you need, so the rest are tree-shaken. Any VS Code grammar or theme JSON can also be loaded at runtime with Language.fromJson and SyntaxTheme.fromJson.

Classes

DartRegexEngine
The default engine. It translates Oniguruma to ECMAScript and runs Dart's built-in RegExp, which is the browser's native engine on the web.
DiffColors
The colors a diff view uses, from a theme's diffEditor.* and editorGutter.* colors, with fallbacks for themes that leave them out. Colors are ARGB integers. Line and word backgrounds are translucent, to paint over the editor background; the chrome colors are opaque.
DiffFileHeaderRow
A file's header: its path, status and change counts. Only files with a path get one.
DiffGapRow
Unchanged lines that are not shown, which a view can offer to expand.
DiffHighlightCache
The highlighting and word changes a diff view needs per file, computed the first time a file is asked for.
DiffHunk
A run of changes with its surrounding context, the part of a patch that starts with @@ -oldStart,oldCount +newStart,newCount @@.
DiffHunkHeaderRow
The @@ line that starts a hunk.
DiffLabels
The words a diff view shows, and announces to screen readers.
DiffLayout
Random-access layout storing runs instead of one object per visible line. Constructing and expanding a large context region costs one block, while accessing an individual row takes logarithmic time.
DiffLine
One line of a hunk.
DiffLineRow
One line in DiffMode.unified.
DiffNoticeRow
Shown in place of a file's lines.
DiffPairRow
One row in DiffMode.split. A context line is on both sides; a removed line without an added partner, or the reverse, leaves one side empty.
DiffRow
One row of a diff view, as laid out by layoutDiff.
DiffSegment
A piece of a diff line with one style. changed marks the words that differ from the paired line, which views give a stronger background.
DocumentLine
One line of a TokenizedDocument.
FileDiff
The changes to one file.
Grammar
A compiled TextMate grammar.
HighlightedDiff
Syntax colors for both sides of a FileDiff.
Highlighter
Tokenizes and themes code with TextMate grammars.
HtmlDecoration
Safe token decoration for static HTML output. Text and attributes are escaped.
Language
A language a Highlighter can tokenize: a TextMate grammar plus its name and aliases.
LineTokens
The tokens of one line, and the state to pass to the next line.
RegexEngine
A regex backend for the tokenizer.
RowHeightIndex
Prefix sums for measured row heights. Updates and lookup are logarithmic.
ScanMatch
One scanner match. Offsets are UTF-16 code unit indices into the line. A group that did not take part in the match reports -1.
Scanner
Finds the earliest match among a fixed list of patterns.
ScopeStack
An immutable stack of scope names, innermost last, for example source.dart > string.interpolated.single.dart.
StateStack
Tokenizer state at a line boundary: the stack of open grammar rules.
StyledRange
A run of text with one style, as UTF-16 offsets into a whole document.
SyntaxTheme
A VS Code color theme: the JSON of a *-color-theme.json file.
ThemedToken
A token with its text and resolved style.
Token
A run of text with the scopes that apply to it.
TokenFontStyle
Font style flags. They can be combined, for example TokenFontStyle.bold | TokenFontStyle.italic.
TokenizedDocument
A document whose lines stay tokenized as its text changes.
TokenStyle
The resolved look of a token. Colors are ARGB integers, as 0xAARRGGBB.
WordChanges
The changed words within edited lines, for highlighting what changed inside a line rather than only which lines changed.

Enums

DiffIndicators
Change markers independent of line background colors.
DiffLineKind
The role of a line in a diff.
DiffMode
How a diff view arranges changed lines.
DiffNotice
Why a file shows a notice instead of lines. Renderers choose the wording.
FileDiffKind
What happened to a file.
HunkSeparatorStyle
Built-in presentation of context gaps and section metadata.
InlineDiffMode
Inline comparison policy, independent of the surrounding line diff. Granularity of bounded inline change highlighting.

Extensions

HighlighterRendering on Highlighter
One-call rendering helpers.

Functions

alphaBlend(int foreground, int background) → int
Paints foreground over background and returns the opaque result, like Flutter's Color.alphaBlend. Both are ARGB integers. For renderers that can't blend, such as terminals.
colorToHex(int argb) → String
Formats an ARGB color as #rrggbb, or #rrggbbaa if not opaque.
diffTexts(String oldText, String newText, {String path = '', int contextLines = 3, bool indentHeuristic = true, String? id, int revision = 0, String? language}) → FileDiff
Compares two versions of a file line by line, like git diff.
layoutDiff(List<FileDiff> files, {DiffMode mode = DiffMode.unified, Set<int> collapsed = const {}, Set<DiffGapId> expanded = const {}}) → List<DiffRow>
Lays out files as the rows a diff view shows, top to bottom.
parseHexColor(String? hex) → int?
Parses #rgb, #rgba, #rrggbb or #rrggbbaa to ARGB. Returns null for anything else.
parsePatch(String patch) → List<FileDiff>
Parses a unified diff, such as the output of git diff or diff -u, into one FileDiff per file.
renderAnsi(List<List<ThemedToken>> lines, SyntaxTheme theme, {bool background = false}) → String
Renders highlighted lines with 24-bit ANSI escape codes, for terminals. Set background to paint the theme's background across each full row.
renderDiffHtml(Iterable<FileDiff> files, {required Highlighter highlighter, required Map<String, SyntaxTheme> themes, DiffMode mode = DiffMode.unified, InlineDiffMode inlineDiffMode = InlineDiffMode.mergedWords, bool expandAll = false, bool wrap = false, HtmlDecoration? decorateLine(FileDiff file, DiffLine line)?}) → String
Renders a static file patch with unified or aligned split rows.
renderHtml(List<List<ThemedToken>> lines, SyntaxTheme theme) → String
Renders highlighted lines as a <pre> block with inline styles, in the same shape as Shiki's codeToHtml.
splitLines(String code) → List<String>
Splits code into lines on \n, dropping a \r before each break.
themeTokens(String line, List<Token> tokens, SyntaxTheme theme) → List<ThemedToken>
Applies theme to one line's raw tokens, merging adjacent tokens with the same style. tokens must come from tokenizing line.

Typedefs

CharRange = ({int end, int start})
A half-open range of UTF-16 offsets within a line.
DiffGapId = ({int file, int hunk})
The unchanged lines before hunk hunk of file file, or after the file's last hunk when hunk equals its hunk count.
GapExpansion = ({int after, int before})
Number of context lines revealed from the beginning and end of a gap.
GrammarLookup = Map<String, Object?>? Function(String scopeName)
Looks up grammars by scope name, for include: "source.other".
InjectionLookup = List<String> Function(String code)
Scope names of grammars that inject into scopeName through their injectionSelector, such as a SQL-in-template-strings grammar for source.js.
UnsupportedPatternCallback = void Function(String pattern, Object error)
Called for a pattern that the engine cannot compile. Such a pattern never matches, and the rest of the grammar keeps working.

Exceptions / Errors

UnsupportedPatternException
An Oniguruma pattern that has no ECMAScript equivalent, such as one using absent operators.