Skip to content
Talk to an engineerRequest access

Lookup and detection

Find a language by name, alias or file name with LanguageRegistry, highlight languages inside languages, and guess an unknown language with LanguageDetector.

A LanguageRegistry finds languages by name, alias or file name. allLanguagesRegistry() holds every built-in language and falls back to genericLanguage:

import 'package:val_highlight/languages/all.dart';
final registry = allLanguagesRegistry();
registry.lookup('kt'); // kotlinLanguage
registry.lookup('YML'); // yamlLanguage: case is ignored
registry.lookup('something-unknown'); // null
registry.resolve('something-unknown'); // genericLanguage, the fallback
registry.forFileName('lib/main.dart'); // dartLanguage
registry.forFileName('Dockerfile'); // dockerfileLanguage
registry.forFileName('build.gradle.kts'); // kotlinLanguage
registry.resolveFileName('notes.xyz'); // genericLanguage

forFileName takes a name or a path, and matches a whole file name such as Dockerfile or CMakeLists.txt before the extension. The language list shows every language’s names and files.

Build a smaller registry from only the languages you ship, with an optional fallback:

final registry = LanguageRegistry(
[dartLanguage, jsonLanguage, yamlLanguage],
plainTextLanguage,
);
registry.add(bashLanguage, aliases: ['terminal']);

A later registration replaces an earlier one under the same name.

HTML highlights the content of <style> as CSS and <script> as JavaScript, with no setup; vue and svelte are aliases of HTML.

Markdown highlights each fenced code block in the language named on its fence, such as json or py, and finds that language in a registry. Give one to whatever does the highlighting:

final registry = allLanguagesRegistry();
Highlighter(registry: registry); // Dart
IncrementalHighlighter(language: markdownLanguage, registry: registry); // editors
CodeHighlighter(registry: registry); // CodeView
HighlightTextController(language: markdownLanguage, registry: registry); // fields

Without a registry, fenced code gets the plain code scope. With one, a fence in a language the registry lacks gets the registry’s fallback — genericLanguage for allLanguagesRegistry() — or, with no fallback, the code scope. A fence ends at its closing fence even inside an unterminated string of the embedded language, the way </script> ends a script.

LanguageDetector guesses the language of a piece of code. It tries, in order:

  1. the file name, when you pass fileName — a whole name such as Dockerfile, then the extension;
  2. a #! first line, against each grammar’s shebangs;
  3. a score over the start of the code (up to sampleSize characters, 4,096 by default): each of a grammar’s signatures patterns that matches adds signatureWeight, each keyword, literal or built-in type found by highlighting the sample adds keywordWeight, and each invalid token subtracts invalidPenalty. The highest score of at least minimumScore wins.
const detector = LanguageDetector();
final detection = detector.detect('def f(x):\n return x * 2\n', allLanguages);
detection?.language; // pythonLanguage
detection?.reason; // 'content'
detector.detect('', allLanguages, fileName: 'src/lib.rs')?.reason; // 'file name'
detector.detect('#!/usr/bin/env python3\n…', allLanguages)?.reason; // 'shebang'
detector.detect('hello there', allLanguages); // null

detect returns a Detection with the language, a score and the reason, or null when nothing scores high enough. A score only means something compared with other candidates for the same input. genericLanguage and plainTextLanguage are never detected: their detectable is false.

Detection is a heuristic. When you know the language, pass it.

Languages addressable by name, alias, file name or file extension.

LanguageRegistry([
Iterable<Grammar> languages = const [],
Grammar? fallback,
])

Creates a registry containing languages.

fallback is used by resolve and resolveFileName when nothing matches, and for embedded code (such as Markdown fences) in a language the registry does not have.

Field Type Description
fallback Grammar? Language used when nothing matches, or null.
Member Type Description
languages List<Grammar> Registered languages, in registration order.
add(Grammar language, {List<String> aliases = const []}) void Registers language under its name, its aliases and any extra aliases. Later registrations replace earlier ones for the same key.
lookup(String nameOrAlias) Grammar? Language registered as nameOrAlias, or null.
resolve(String nameOrAlias) Grammar? Language registered as nameOrAlias, else fallback.
resolveFileName(String fileName) Grammar? Language for fileName, matched as forFileName does, else fallback.
forFileName(String fileName) Grammar? Language for fileName (a path is fine), matched by whole name, such as Dockerfile, then by extension, such as main.dart; or null.

Thrown when a language name is not registered.

const UnknownLanguageException(String name)

Creates the exception for name.

Field Type Default Description
name String required The name that was not found.

Guesses the language of a piece of code.

Checks run from cheapest and surest to most expensive:

  1. the file name, when given: a whole name such as Dockerfile, then the extension;
  2. a #! first line against Grammar.shebangs;
  3. a content score over the first sampleSize characters: each Grammar.signatures pattern that matches adds signatureWeight, and each keyword, literal or built-in type found by highlighting the sample adds keywordWeight. Invalid tokens subtract invalidPenalty.

This is a heuristic. When you know the language, pass it instead.

const LanguageDetector({
int sampleSize = 4096,
double signatureWeight = 10,
double keywordWeight = 1,
double invalidPenalty = 5,
double minimumScore = 3,
})

Creates a detector.

Field Type Default Description
sampleSize int 4096 Characters of input examined for the content score.
signatureWeight double 10 Score added per matching signature pattern.
keywordWeight double 1 Score added per keyword-like token.
invalidPenalty double 5 Score subtracted per invalid token.
minimumScore double 3 Content scores below this are treated as “unknown”.
Member Type Description
detect(…) Detection? Detects the language of code among candidates, or returns null when nothing scores at least minimumScore.

A detected language and how confident the detector is.

const Detection(
Grammar language,
double score, {
String reason = 'content',
})

Creates a detection result.

Field Type Default Description
language Grammar required The detected language.
score double required Detection score. Higher is more confident; only useful for comparing candidates for the same input.
reason String 'content' Why this language won: file name, shebang or content.

Every built-in language.

const List<Grammar> allLanguages

A registry of every built-in language, for lookup by name, alias or file name, and for Markdown code fences. Unknown names fall back to genericLanguage.

LanguageRegistry allLanguagesRegistry()