Skip to content
Talk to an engineerRequest access

Writing a grammar

Write a language for val_highlight from building blocks — comments, strings, numbers, keywords — and the rules underneath them.

A language is a Grammar: a const list of rules, plus named rule lists to reuse. Import package:val_highlight/advanced.dart for the rule classes. The built-in languages are written with exactly this API — read lib/languages/ for examples.

Most grammars need no regular expressions:

import 'package:val_highlight/advanced.dart';
const confLanguage = Grammar(
name: 'conf',
fileExtensions: ['conf'],
rules: [
LineComment(';'),
LineComment('#', afterSpace: true),
QuotedString('"'),
Numbers(),
KeywordRule({Scopes.literal: ['true', 'false', 'on', 'off']}),
Operators('='),
],
);
Block Covers
LineComment('//') A comment to the end of the line. With afterSpace: true it only starts at a line start or after whitespace, so # inside a word is left alone.
BlockComment('/*', '*/') A delimited comment; nested: true where comments nest.
QuotedString('"') A string with escapes. Options: end, prefix, escape, doubled quotes, multiline, lastInRun and inner rules. A string that isn’t multiline also ends at the end of its line.
Interpolation(r'${', '}') An expression inside a string, with balanced braces.
Numbers() Decimals, floats with exponents, hex, binary and octal, with an optional digit separator and suffix.
Operators('+-*/=') Runs of operator characters.
Annotation('@') Annotations, attributes and decorators.
Preprocessor('#') #include-style lines, with \ continuations.
KeywordRule({…}) Word lists per scope, found by table lookup, with otherwise rules for words not in the lists.
CommonRules.capitalizedType, functionCall, memberCall, member Heuristics for identifiers that are not keywords, for KeywordRule.otherwise.

Extend BlockRule and implement expand() to make blocks of your own.

Rule What it does
TokenRule(pattern, scope:, captures:) Matches a regular expression and gives it a scope; captures scopes capture groups.
RegionRule(begin:, end:, scope:, rules:) A section with its own rules inside, such as a string or a comment. Regions nest. end is tried before the inner rules.
IncludeRule('name') Inserts a named rule list from the grammar’s repository; IncludeRule.self inserts the top-level rules.

How matching works:

  • The earliest match wins. Among rules that match at the same position, the one listed first wins.
  • Patterns are Dart RegExp sources compiled in multi-line mode, so ^ and $ match at line boundaries. Named capture groups are not allowed, because a state’s rules are combined into one expression.
  • A grammar is compiled the first time it is used. grammar.validate() compiles all of it at once and throws GrammarException for a bad pattern, an unknown include or an include cycle — call it in a test.

More RegionRule options:

  • endReferencesBegin: true lets \1 to \9 in end stand for text begin captured — heredocs, raw strings, Markdown fences.
  • embed: someGrammar highlights the region’s content in another language; embedCapture: n takes the language’s name from a capture group of begin and looks it up in the highlighter’s registry. The region’s end closes it from any depth of the embedded language.
  • beginScope, endScope, beginCaptures and endCaptures style the delimiters.

Keeping it fast. Start patterns with something specific — a literal, a small character class, or ^ for line-start rules — rather than ., a negated class or a lookbehind. The scanner works out which characters each pattern can start with and only tries the rules that can match at a position; see performance.

Option What it does
aliases, fileExtensions, fileNames The names and files the language is found by. Whole file names win over extensions.
repository Named rule lists for IncludeRule.
caseInsensitive Patterns and keywords ignore case.
unicode Patterns are compiled in unicode mode.
shebangs, signatures Hints for detection: interpreter names for #! lines, and patterns that strongly suggest the language.
detectable Whether LanguageDetector may pick the grammar. Defaults to true.
restartLine Lines no rule looks past. Incremental highlighting normally resumes a line before an edit; a grammar whose rules read further ahead (Markdown’s inline code can wrap a whole paragraph) sets this, and resuming starts at the nearest earlier matching line.
editing The EditingSyntax editors use.

EditingSyntax tells an editor such as CodeField how the language is edited: lineComment, blockComment, brackets (default ()[]{}) and quotes (default " and '). Every built-in language sets one. For your own grammar, set editing, or leave it out and EditingSyntax.of(grammar) derives it from the grammar’s blocks: the shortest LineComment and BlockComment markers (the first of equal length), and the quotes of single-character QuotedStrings.

EditingSyntax.of(confLanguage).lineComment; // ';'
EditingSyntax.of(confLanguage).quotes; // '"'
EditingSyntax.of(pythonLanguage).lineComment; // '#'

Presets: EditingSyntax.cStyle (// and /* */), hashStyle (#), markupStyle (<!-- -->) and none.

To contribute a language — with golden snapshots, edge-case tests and a gallery sample — follow CONTRIBUTING.md.

A language grammar: an ordered list of Rules plus a named repository of reusable rule lists.

Grammars are immutable and usually const, so an unused grammar costs nothing and is tree-shaken away. A grammar is compiled lazily the first time it is used and the compiled form is cached for its lifetime.

When several rules can match, the one that starts earliest wins. Among rules starting at the same position, the one listed first wins.

const Grammar({
required String name,
required List<Rule> rules,
List<String> aliases = const [],
List<String> fileExtensions = const [],
List<String> fileNames = const [],
Map<String, List<Rule>> repository = const {},
bool caseInsensitive = false,
bool unicode = false,
List<String> shebangs = const [],
List<String> signatures = const [],
String? restartLine,
bool detectable = true,
EditingSyntax? editing,
})

Creates a grammar.

Field Type Default Description
name String required Canonical, lower-case language name, such as dart.
aliases List<String> const [] Other names this language is known by, such as js for javascript.
fileExtensions List<String> const [] File extensions without the dot, such as dart or json.
fileNames List<String> const [] Whole file names, such as Dockerfile or CMakeLists.txt. These take priority over fileExtensions.
rules List<Rule> required Rules active at the top level of a document.
repository Map<String, List<Rule>> const {} Named rule lists that IncludeRule can reference.
caseInsensitive bool false Whether patterns and keywords ignore case.
unicode bool false Whether patterns are compiled in unicode mode.
shebangs List<String> const [] Interpreter names that identify this language in a #! first line, such as python or bash. Used by language detection.
signatures List<String> const [] Patterns that strongly suggest this language, such as ^import 'package:. Used by language detection.
restartLine String? Lines that no rule looks past, such as blank lines in Markdown.
detectable bool true Whether LanguageDetector may pick this grammar. Off for catch-all grammars such as plain text and the generic fallback.
editing EditingSyntax? How code in this language is edited: comment markers, brackets and quotes. When null, EditingSyntax.of derives them from the grammar’s comment and string blocks.
restartLine: more

After an edit, IncrementalHighlighter normally re-scans from the line before the edit, which is enough when no rule’s pattern reads more than one line ahead. A grammar whose rules can (a Markdown code span may wrap across a whole paragraph) sets this, and re-scanning then starts at the nearest earlier line matching it.

Member Type Description
extend({…}) Grammar Returns a new grammar based on this one.
withKeywords({…}) Grammar Returns this grammar with its keyword tables changed.
validate() void Compiles every part of the grammar now, so mistakes surface at once instead of the first time a region is used.
extend: more

rules are placed before the existing top-level rules, so they take priority. repository entries are added, replacing entries with the same name. This is how you add or override syntax without rewriting a grammar.

withKeywords: more

add maps a scope to words that get it, such as {Scopes.keyword: ['defer']}; a word already in another scope moves. Words in remove are removed from every scope, so they highlight like any other identifier. Applies to every KeywordRule in the grammar, including those inside regions and the repository.

final myDart = dartLanguage.withKeywords(
add: {Scopes.typeBuiltin: ['Widget', 'BuildContext']},
remove: ['get', 'set'],
);
validate: more

Throws GrammarException for an invalid pattern, an unknown include or an include cycle.

A single grammar rule.

Patterns are Dart RegExp sources compiled with multiLine: true, so ^ and $ match at line boundaries. Named capture groups are not allowed, because rules are combined into a single expression per state.

const Rule()

Base constructor for rules.

Matches pattern and marks the match with scope.

captures maps capture group numbers inside pattern to scopes. Captured groups must appear in order and must not overlap.

const TokenRule(
String pattern, {
String? scope,
Map<int, String> captures = const {},
})

Creates a token rule.

Field Type Default Description
pattern String required Regular expression source to match.
scope String? Scope for the whole match, or null for no scope.
captures Map<int, String> const {} Scopes for capture groups inside pattern, keyed by group number.

A region that starts at begin and ends at end, with its own rules active in between.

Regions nest: strings containing interpolations, comments containing nested comments, and so on. The end pattern is tried before rules at the same position.

A region can hand its content to another language: set embed to a grammar (for example CSS inside an HTML <style> element), or set embedCapture to a capture group of begin whose text names the language (for example the info string of a Markdown code fence). Named languages are looked up in the Highlighter’s registry; when none is found, rules apply instead. The end of an embedding region closes it from any depth: a code fence ends even inside an unterminated string of the embedded language, just as </script> ends a script in a browser.

Set endReferencesBegin when the end depends on what the begin matched, such as a heredoc delimiter: \1–\9 in end then stand for the text of those capture groups of begin.

const RegionRule({
required String begin,
required String end,
String? scope,
String? beginScope,
String? endScope,
Map<int, String> beginCaptures = const {},
Map<int, String> endCaptures = const {},
List<Rule> rules = const [],
Grammar? embed,
int? embedCapture,
bool endReferencesBegin = false,
})

Creates a region rule.

Field Type Default Description
begin String required Pattern that opens the region.
end String required Pattern that closes the region.
scope String? Scope for the whole region, including both delimiters.
beginScope String? Extra scope for the opening delimiter, nested inside scope.
endScope String? Extra scope for the closing delimiter, nested inside scope.
beginCaptures Map<int, String> const {} Scopes for capture groups inside begin.
endCaptures Map<int, String> const {} Scopes for capture groups inside end.
rules List<Rule> const [] Rules active inside the region.
embed Grammar? Language used for the region’s content instead of rules.
embedCapture int? Capture group of begin naming the language for the content.
endReferencesBegin bool false Whether \1–\9 in end refer to capture groups of begin.

Matches words with word and scopes them by table lookup.

A lookup is much faster than one large alternation of every keyword. keywords maps a scope to the words that get it. When a matched word is not in the table, each rule in otherwise is tried at the same position, which is how heuristics such as “capitalised words are types” work.

const KeywordRule(
Map<String, List<String>> keywords, {
String word = r'(?<!\w)[A-Za-z_]\w*',
List<TokenRule> otherwise = const [],
})

Creates a keyword rule.

Field Type Default Description
keywords Map<String, List<String>> required Scope to words, such as {'keyword': ['if', 'else']}.
word String r'(?<!\w)[A-Za-z_]\w*' Pattern for a single word.
otherwise List<TokenRule> const [] Rules tried, in order, on words that are not keywords.

Inserts the rules of a Grammar.repository entry in place.

Use IncludeRule.self to include the grammar’s top-level rules.

const IncludeRule(String name)

Creates a reference to the repository entry called name.

Field Type Default Description
name String required Repository entry name, or $self.
Member Type Description
static self IncludeRule Includes the grammar’s top-level rules.

A reusable rule that expands into basic rules when the grammar is compiled.

The built-in blocks cover what most languages repeat: comments, strings, numbers, operators and annotations, so most grammars need no regular expressions. Extend this class to make your own blocks.

const BlockRule()

Base constructor for blocks.

Member Type Description
expand() List<Rule> The basic rules this block stands for. Called once per block.

A comment from start to the end of the line, such as // or #.

With afterSpace, the comment only starts at the beginning of a line or after whitespace, so # inside words (a#b, $#) is left alone.

const LineComment(
String start, {
String scope = Scopes.comment,
bool afterSpace = false,
})

Creates a line comment block.

Field Type Default Description
start String required Text that starts the comment.
scope String Scopes.comment Scope of the comment.
afterSpace bool false Whether the comment must follow whitespace or start a line.

A comment between open and close, such as /* and */.

With nested, inner open … close pairs nest, as in Dart, Rust, Swift and Haskell.

const BlockComment(
String open,
String close, {
bool nested = false,
String scope = Scopes.comment,
List<Rule> rules = const [],
})

Creates a block comment block.

Field Type Default Description
open String required Text that opens the comment.
close String required Text that closes the comment.
nested bool false Whether comments nest.
scope String Scopes.comment Scope of the comment.
rules List<Rule> const [] Extra rules inside the comment, such as doc tags.

A string between quote and end (default: quote).

  • prefix is a pattern allowed before the quote, such as [rRbB]?.
  • escape starts an escape sequence (default \); null for none.
  • doubled treats a doubled quote as an escaped quote (SQL, Pascal, VB, CSV).
  • multiline lets the string span lines; otherwise it also ends at the end of the line, so an unclosed quote cannot swallow the file.
  • lastInRun closes on the last delimiter of a run of quote characters, as Scala and Kotlin """ strings do: """"x"""" holds "x".
  • rules adds rules inside, such as interpolation.
const QuotedString(
String quote, {
String? end,
String? prefix,
String? escape = r'\',
bool doubled = false,
bool multiline = false,
bool lastInRun = false,
List<Rule> rules = const [],
String scope = Scopes.string,
})

Creates a string block.

Field Type Default Description
quote String required Opening quote.
end String? Closing quote, when different from quote.
prefix String? Pattern allowed immediately before the quote.
escape String? r'\' Escape character, or null for none.
doubled bool false Whether a doubled closing quote is an escape.
multiline bool false Whether the string may span lines.
lastInRun bool false Whether the string closes on the last delimiter of a run of quotes.
rules List<Rule> const [] Extra rules inside the string.
scope String Scopes.string Scope of the string.

An interpolated expression inside a string, such as ${…} or #{…}.

Braces inside the expression are balanced before close ends it. rules default to the grammar’s top level.

const Interpolation(
String open,
String close, {
List<Rule> rules = const [IncludeRule.self],
String scope = Scopes.interpolation,
})

Creates an interpolation block.

Field Type Default Description
open String required Text that opens the expression.
close String required Text that closes the expression.
rules List<Rule> const [IncludeRule.self] Rules inside the expression.
scope String Scopes.interpolation Scope of the expression.

Numeric literals: decimals, floats with exponents, and hexadecimal, binary and octal forms.

separator is the digit separator (_, or ' in C++), or null. suffix is a pattern for type suffixes, such as [uUlLfF]* or n?.

const Numbers({
bool hex = true,
bool binary = true,
bool octal = true,
String? separator = '_',
String suffix = '',
String scope = Scopes.number,
})

Creates a number block.

Field Type Default Description
hex bool true Whether 0x… is a number.
binary bool true Whether 0b… is a number.
octal bool true Whether 0o… is a number.
separator String? '_' Digit separator, or null.
suffix String '' Pattern for a suffix after the number.
scope String Scopes.number Scope of numbers.

Runs of operator characters, such as +, == or >>=.

const Operators([
String chars = '+-*/%=<>!&|^~?:',
String scope = Scopes.operator,
])

Creates an operator block matching runs of chars.

Field Type Default Description
chars String '+-*/%=<>!&|^~?:' Characters that make up operators.
scope String Scopes.operator Scope of operators.

Annotations, attributes and decorators, such as @override or @app.route.

const Annotation([
String sigil = '@',
String scope = Scopes.meta,
])

Creates an annotation block starting with sigil.

Field Type Default Description
sigil String '@' Character that starts an annotation.
scope String Scopes.meta Scope of annotations.

Preprocessor lines such as #include <x> or #define X 1, including lines continued with a trailing backslash.

const Preprocessor([
String sigil = '#',
String scope = Scopes.meta,
])

Creates a preprocessor block starting with sigil.

Field Type Default Description
sigil String '#' Character that starts a directive.
scope String Scopes.meta Scope of directives.

Common heuristics for identifiers that are not keywords, for use in KeywordRule.otherwise.

Member Type Description
static capitalizedType TokenRule A capitalised identifier is a type (Foo, _Bar).
static functionCall TokenRule An identifier followed by ( or <T>( is a function.
static memberCall TokenRule After a ., a called name is a function (list.add().
static member TokenRule After a ., any other name is a plain member, never a keyword.

C keywords (C23 included).

const List<String> cKeywords

C built-in and standard types.

const List<String> cTypes

C literals.

const List<String> cLiterals

Rules shared by C, C++ and Objective-C.

const List<Rule> cCommonRules

How code in a language is edited: its comment markers, brackets and quotes.

Editors use this to toggle comments, auto-close brackets and quotes and match brackets. Set it on a grammar with Grammar.editing; read it with EditingSyntax.of, which derives one from the grammar’s LineComment, BlockComment and QuotedString blocks when none is set.

const myLanguage = Grammar(
name: 'mine',
rules: [...],
editing: EditingSyntax(lineComment: '--', quotes: '"'),
);
const EditingSyntax({
String? lineComment,
(String, String)? blockComment,
String brackets = '()[]{}',
String quotes = '"\'',
})

Creates editing conventions for a language.

Field Type Default Description
lineComment String? Text that starts a line comment, such as // or #, or null if the language has none.
blockComment (String, String)? The opening and closing text of a block comment, such as ('/*', '*/'), or null if the language has none.
brackets String '()[]{}' Bracket pairs, as consecutive opening and closing characters: '()[]{}' stands for (), [] and {}. Used for matching and auto-closing.
quotes String '"\'' Characters that open and close a string, such as " and '. Auto-closed like brackets, except after a letter or digit, so don't is left alone. Leave out characters with another meaning, such as ' in Rust lifetimes or Lisp quoting.
Member Type Description
static cStyle EditingSyntax // line comments, /* */ block comments, and " ' quotes: C, Java, Kotlin, Swift and most of their relatives.
static hashStyle EditingSyntax # line comments: shells, Python, Ruby, YAML and many config formats.
static markupStyle EditingSyntax <!-- --> block comments: HTML, XML and Markdown.
static none EditingSyntax No comments, brackets or quotes: plain text.
copyWith({…}) EditingSyntax Returns a copy with the given fields replaced.
closerOf(String open) String? The closing character for open, or null if open opens nothing.
static of(Grammar grammar) EditingSyntax The editing conventions of grammar: its Grammar.editing, or, when that is unset, conventions derived from its comment and string blocks.
closerOf: more

Brackets close with their pair and quotes with themselves.

static of: more

Derivation looks at the top-level rules and the repository. The shortest LineComment and BlockComment markers win, so // beats ///. Quotes come from single-character QuotedStrings, and default to " and ' when there are none. The result is cached per grammar.

Thrown when a grammar is invalid: a bad pattern, an unknown include or an include cycle.

const GrammarException(String grammar, String message)

Creates a grammar exception.

Field Type Default Description
grammar String required Name of the grammar that failed.
message String required What went wrong.