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.
Look up a language
Section titled “Look up a language”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'); // kotlinLanguageregistry.lookup('YML'); // yamlLanguage: case is ignoredregistry.lookup('something-unknown'); // nullregistry.resolve('something-unknown'); // genericLanguage, the fallbackregistry.forFileName('lib/main.dart'); // dartLanguageregistry.forFileName('Dockerfile'); // dockerfileLanguageregistry.forFileName('build.gradle.kts'); // kotlinLanguageregistry.resolveFileName('notes.xyz'); // genericLanguageforFileName 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.
Languages inside languages
Section titled “Languages inside languages”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); // DartIncrementalHighlighter(language: markdownLanguage, registry: registry); // editorsCodeHighlighter(registry: registry); // CodeViewHighlightTextController(language: markdownLanguage, registry: registry); // fieldsWithout 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.
Detect a language
Section titled “Detect a language”LanguageDetector guesses the language of a piece of code. It tries, in
order:
- the file name, when you pass
fileName— a whole name such asDockerfile, then the extension; - a
#!first line, against each grammar’sshebangs; - a score over the start of the code (up to
sampleSizecharacters, 4,096 by default): each of a grammar’ssignaturespatterns that matches addssignatureWeight, each keyword, literal or built-in type found by highlighting the sample addskeywordWeight, and each invalid token subtractsinvalidPenalty. The highest score of at leastminimumScorewins.
const detector = LanguageDetector();
final detection = detector.detect('def f(x):\n return x * 2\n', allLanguages);detection?.language; // pythonLanguagedetection?.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); // nulldetect 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.
API reference
Section titled “API reference”LanguageRegistry
Section titled “LanguageRegistry”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. |
UnknownLanguageException
Section titled “UnknownLanguageException”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. |
LanguageDetector
Section titled “LanguageDetector”Guesses the language of a piece of code.
Checks run from cheapest and surest to most expensive:
- the file name, when given: a whole name such as
Dockerfile, then the extension; - a
#!first line againstGrammar.shebangs; - a content score over the first
sampleSizecharacters: eachGrammar.signaturespattern that matches addssignatureWeight, and each keyword, literal or built-in type found by highlighting the sample addskeywordWeight. Invalid tokens subtractinvalidPenalty.
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. |
Detection
Section titled “Detection”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. |
allLanguages
Section titled “allLanguages”Every built-in language.
const List<Grammar> allLanguagesallLanguagesRegistry
Section titled “allLanguagesRegistry”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()