Skip to content

Language Extensions

SS-YYC edited this page Nov 17, 2026 · 3 revisions

Language extensions

A language extension teaches Kodo about a file type. It always does two things:

  1. Claims file extensions, so Kodo knows a .myl file is a MyLang file.
  2. Provides an engine, so Kodo knows what to do with it.

Pick a primary engine. Engines can combine in one package (for example, LSP for language features plus language.json for the base highlighting profile - language.json is parsed for every language package), but one primary engine per concern is the norm. This guide covers all three in full.

Engine Use when You write Needs a server?
Legacy You only need syntax highlighting language.json No
LangRules A community or smaller language that has no server A .NET assembly No
LSP An established language that has a real server Manifest JSON Yes

Every language package needs a manifest.json:

{
  "id": "mylang-kodo-extension",
  "version": "1.0.0",
  "name": "MyLang",
  "type": "language",
  "author": "Your Name",
  "description": "Support for MyLang files.",
  "extensions": [".myl"],
  "langRulesOptions": {
    "warnOnImplicitVariables": "true"
  }
}

extensions entries must include the leading dot. Every other manifest.json field is covered in Kodo file format.


Choosing an engine

Start with Legacy. If language.json gives you the highlighting you want, you are done. It is pure data, has no build step, cannot crash the editor, and updates instantly when you edit the file.

Move to LangRules when highlighting is not enough - you want completions, hover, or navigation

  • and no language server exists for your language. Be honest about the cost before you start:

  • You are writing a parser. Every edge case in the language is your problem.

  • Diagnostics run in Kodo's isolated Insight worker and receive cancellation. Other provider capabilities may run in Kodo's process; keep every method bounded and avoid blocking I/O.

  • You must handle incomplete input gracefully. Users type half a token constantly; every method will be called on broken code, on every keystroke.

  • Nothing validates your output. A range outside the document, or a start/length pair that overflows, produces visibly wrong behaviour.

Move to LSP whenever a server exists. You write configuration, not a parser. The server is maintained by the language's community, and you get correctness for free.

If a language has a server, use LSP. Do not reimplement a parser that already exists.


1. Legacy

Legacy packages contain no code at all - just language.json. Kodo's built-in tokenizers read it and color your file. This is the whole engine.

Shipped examples of this shape: Shine, HolyC, KSP-Module-Manager-Config.

Legacy walkthrough

Create a folder with manifest.json (above) and language.json:

{
  "extensions": [".myl"],
  "keywords": ["if", "else", "while", "for", "return", "func", "var", "const"],
  "types": ["int", "float", "string", "bool", "MyClass"],
  "functions": ["print", "len", "push"],
  "properties": [],
  "namespaces": [],
  "commentLine": "#",
  "stringDelimiters": ["\""],
  "colorTokens": {
    "keyword": "#569CD6",
    "type": "#4EC9B0",
    "function": "#DCDCAA",
    "string": "#CE9178",
    "comment": "#6A9955"
  }
}

Drop the folder into %LocalAppData%\Kodo\Extensions\. Kodo picks up a new folder or a new .kox without a restart, but editing language.json in place does not reload it - the folder watcher only reacts to created, deleted, and renamed files, and it ignores language.json by name. Use the Extensions page's refresh button, or restart Kodo, to see colour edits.

language.json reference

Every field is optional.

Profile scope and Explorer icons

Field Type Meaning
extensions string[] Optional file extensions scoped to this profile. A non-empty list applies this profile only to those extensions; when empty or omitted, the profile merges into the base profile and its file icon settings use the manifest's extensions.
fileIcon string Optional text label for files handled by this profile, shown in Explorer's text-based file icon style.
fileIcons object Optional extension-to-label map. A matching entry overrides fileIcon for that extension.

Icon labels may contain up to 10 letters, digits, +, #, or -. Extensions are written with a leading dot. For example:

{
  "extensions": [".myl", ".mylh"],
  "fileIcon": "MYL",
  "fileIcons": {
    ".myl": "MYL",
    ".mylh": "MYLH"
  }
}

When a profile has both settings, a matching fileIcons entry takes precedence over fileIcon. An invalid chosen label is ignored, and Kodo uses its built-in project, filename, and extension icon rules instead.

Explorer icons built into Kodo

Explorer uses compact text labels rather than per-extension image files. Extensions can add labels for their claimed file types with fileIcon and fileIcons above. Kodo also recognizes common project markers, repository files, and directory roles without depending on a language extension or language server.

Project marker files keep their own identity: for example, .csproj/.sln show .NET labels, Cargo.toml shows CARGO, go.mod shows GO, package.json shows NPM, and CMakeLists.txt shows CMAKE. Supported project markers include .csproj, .fsproj, .vbproj, .sln, .slnx, Cargo.toml, go.mod, package.json, deno.json/.jsonc, Maven and Gradle build files, CMakeLists.txt, Makefiles, .vcxproj, .xcodeproj, Python project files, Package.swift, pubspec.yaml, composer.json, Gemfile, mix.exs, stack.yaml, and *.cabal.

The folder containing one project family gets a short family label (such as NET, RUST, GO, NODE, or PY). A folder with markers from multiple families gets the neutral PRJ label; Kodo does not label every file in a mixed-language repository as if it belonged to one language. Project detection checks the folder's immediate entries, and cached results are invalidated when filesystem changes arrive.

Common repository and documentation files also have named labels. This includes Git dotfiles such as .gitignore, .gitattributes, .gitmodules, .gitkeep, .gitconfig, .git-blame-ignore-revs, and .mailmap; license/copyright/notice files; README files (including README.md); changelog, contributing, security, code-of-conduct, authors/contributors, support, and roadmap documents; and common lockfiles and tool configuration files. README variants use RMD rather than the generic Markdown label.

Directory labels describe common roles, including source, tests, docs, assets, configuration, build output, dependencies, generated files, temporary files, caches, virtual environments, Git, and CI configuration. Names such as bin, obj, target, dist, build, out, release, and artifacts receive build-output labels; generated/gen receive a generated label. These are name-based Explorer cues, not a claim that Kodo has inspected every file or will exclude the folder from search, indexing, or version control.

For extension authors, use fileIcon for one label shared by the profile's extensions, and fileIcons when particular extensions need different labels. Keep labels short (up to ten letters/digits plus +, #, or -) so they fit the existing Explorer icon style. Built-in project-marker and filename-specific labels (such as README and LICENSE) take precedence; profile icons are considered for other matching extensions before the generic file icon fallback.

Token lists - each is an array of strings, matched on word boundaries, so "int" will not match inside "integer".

Field Colors as Notes
keywords keyword Reserved words
types type Built-in and user type names
functions function Function and method names
properties property Property and field names
namespaces namespace Namespace and module names

Lexical structure

Field Default Meaning
commentLine "//" Line comment prefix, e.g. "#"
commentBlockStart "/*" Block comment opener
commentBlockEnd "*/" Block comment closer
stringDelimiters ["\"", "'"] Single-line string delimiters. A span ends at the closing delimiter or end of line.
multiLineStringDelimiters [] Delimiters that span lines, e.g. ["\"\"\""]. List longer delimiters first.
disableSingleQuoteStrings false true stops '…' being treated as a string. Use for C#, where ' also appears as a character literal and in generics.

Insight tuning

Field Meaning
blacklist Names suppressed from autocomplete inside a call to that same name. Case-insensitive.
deadCodeIgnore Names the dead-code scanner must never flag, e.g. __init__, self.
deadCodeEntryPoints Extra implicit entry points beyond the built-ins (main, wmain, winmain, wwinmain, dllmain, _start).

colorTokens overrides highlighting colors. Omit a key to keep the default.

Key Typical use
keyword Reserved words
type Type names
string String literals
charLiteral Character literals
comment Comments
number Numeric literals
operator Operators
punctuation Punctuation
function Function names
property Property names
namespace Namespaces
attribute Attributes/annotations
preprocessor Preprocessor directives
variable Variables
"colorTokens": {
  "keyword": "#569CD6",      "type": "#4EC9B0",
  "string": "#CE9178",       "comment": "#6A9955",
  "number": "#B5CEA8",       "operator": "#D4D4D4",
  "punctuation": "#D4D4D4",  "function": "#DCDCAA",
  "property": "#9CDCFE",     "namespace": "#4FC1FF",
  "attribute": "#C586C0",    "preprocessor": "#C586C0",
  "variable": "#A0DBFD",     "charLiteral": "#CE9178"
}

Several file profiles in one package

A package can carry up to six profiles: language.json plus language1.json through language5.json. Each is parsed independently.

  • If a profile's own extensions array is non-empty, that profile is scoped to just those file extensions.
  • If it is absent or empty, the profile is merged into the base language.

This is how one package covers several related file types. A real example is the C# package: its language.json handles .cs/.csx, and its language2.json scopes .csproj, .props, .targets and friends with completely different comment delimiters (<!-- -->) and its own color map.

// language2.json - scoped to project files only
{
  "extensions": [".csproj", ".props", ".targets"],
  "keywords": ["Project", "PropertyGroup", "ItemGroup", "Target", "PackageReference"],
  "commentBlockStart": "<!--",
  "commentBlockEnd": "-->"
}

2. LangRules

LangRules is for a language that has no language server - typically a community or smaller language. You write a .NET assembly; Kodo loads it and calls into it.

Shipped examples: Python, Rust, TOML, SQL, Bash, Batch, JSON, Markdown, PowerShell, and others.

How the assembly is found

Kodo reads the plugin field of your manifest.json to find the assembly:

{
  "id": "mylang-kodo-extension",
  "version": "1.0.0",
  "name": "MyLang",
  "type": "language",
  "author": "Your Name",
  "description": "Support for MyLang files.",
  "extensions": [".myl"],
  "plugin": "LangRules.dll"
}

This trips people up, so state it plainly: plugin is the field that binds LangRules, not languagePlugin. Every shipped LangRules package uses plugin. See plugin vs languagePlugin.

Kodo loads that one assembly and looks for a type implementing ILangRulesProvider. The same assembly is also scanned for IKodoPlugin implementations, so a single DLL can provide both a LangRules engine and host UI integration.

v2.3 document and workspace analysis

For new providers, implement AnalyzeSyntaxAsync and AnalyzeSemanticsAsync. They receive a LangRulesDocumentContext and a CancellationToken. The interface keeps the original synchronous AnalyzeSyntax(string) and AnalyzeSemantics(string) methods for compatibility; the default async methods call those old methods, so existing providers continue to work. New providers can use async I/O when appropriate, but should prefer in-memory analysis and check cancellation in long loops.

LangRulesDocumentContext contains:

Property Meaning
Uri Stable document URI (file: URI for saved files, untitled: otherwise).
FilePath Full path for saved files, empty for untitled documents.
LanguageId Loaded language extension id, or the file extension when no id is available.
Version Editor snapshot version. Use it to key per-document caches; do not apply results to a newer version.
Text Exact source snapshot being analyzed. All diagnostic ranges index this string.
WorkspaceRoot Open workspace directory, when one exists.
Configuration String options from manifest langRulesOptions.

Kodo builds a LangRulesWorkspaceContext from that root, the current document, and open documents inside the workspace. It currently supplies at most 128 open documents and 2 MB of text; sibling documents larger than 250 KB are omitted. The current document is always first. The snapshot may contain more than one language, so check each document's LanguageId. Closed files are not included; WorkspaceRoot is supplied so providers can discover project configuration when it is useful.

Override AnalyzeWorkspaceAsync for checks that need declarations across open files. Return LangRuleWorkspaceDiagnostic values with the target document's exact Uri; Kodo routes each result to that document's diagnostics. The method runs as each open document is analyzed, so keep the scan bounded, check cancellation, and avoid rescanning large parts of disk on every request.

public Task<IReadOnlyList<LangRuleWorkspaceDiagnostic>> AnalyzeWorkspaceAsync(
    LangRulesWorkspaceContext workspace,
    CancellationToken cancellationToken)
{
    cancellationToken.ThrowIfCancellationRequested();
    var results = new List<LangRuleWorkspaceDiagnostic>();
    foreach (var document in workspace.Documents)
    {
        cancellationToken.ThrowIfCancellationRequested();
        var markerOffset = document.Text.IndexOf("TODO", StringComparison.Ordinal);
        if (markerOffset >= 0)
        {
            var diagnostic = new LangRuleDiagnostic(
                markerOffset, 4, "Remove this TODO before release.",
                "hint", "MY100", "MyLang");
            results.Add(new LangRuleWorkspaceDiagnostic(document.Uri, diagnostic));
        }
    }
    return Task.FromResult<IReadOnlyList<LangRuleWorkspaceDiagnostic>>(results);
}

langRulesOptions is an optional manifest object whose string values are passed unchanged to both document and workspace contexts. Kodo does not assign meaning to the keys; the extension owns their names and defaults. For example:

"langRulesOptions": {
  "warnOnImplicitVariables": "true",
  "maxWorkspaceFiles": "80"
}

Diagnostic model and ranges

LangRuleDiagnostic keeps the original constructor: (Start, Length, Message, Severity, Code, Source). The range is a zero-based UTF-16 offset and length into the exact document text. A zero-length range is valid, including at end-of-file, for missing-token diagnostics. Keep Start between 0 and Text.Length; Kodo clips a length that runs past the end of the document.

Property Use
Severity error, warning, info, or hint (fatal and critical map to error).
Code Stable diagnostic identifier, such as MY001; code actions can match it.
Source Short provider or analyzer name shown with the diagnostic.
CodeDescriptionUri Optional help page URL for the diagnostic code.
Tags LangRuleDiagnosticTag.Unnecessary or .Deprecated; shown in diagnostic details.
RelatedInformation Other document URI, UTF-16 start/length, and explanation. Kodo shows up to three related locations in the diagnostic details.
Data Optional explanatory text shown in diagnostic details.

Kodo displays the message and severity as the diagnostic, and shows source, code, tags, related locations, code-description URL, and Data in its diagnostic details popup. A provider exception is logged and returned as a KODO-LANGRULES-FAILURE warning with an extension diagnostic log hint; OperationCanceledException is treated as normal cancellation. The analysis runs in Kodo's isolated Insight worker, and the host rejects stale results after the document changes.

Diagnostic-aware code actions

The new GetCodeActionsAsync(LangRulesCodeActionContext, CancellationToken) method receives the document snapshot, caret offset, and diagnostics at the caret or on its line. Use their Code values to offer targeted fixes. Its default implementation calls the original GetCodeActions(string, int) method for compatibility.

public Task<IReadOnlyList<LangRuleCodeAction>> GetCodeActionsAsync(
    LangRulesCodeActionContext context,
    CancellationToken cancellationToken)
{
    cancellationToken.ThrowIfCancellationRequested();
    var actions = context.Diagnostics
        .Where(diagnostic => diagnostic.Code == "MY010")
        .Select(diagnostic => new LangRuleCodeAction(
            "Replace with 'print'", "quickfix", diagnostic.Start, diagnostic.Length,
            "print", diagnostic.Code))
        .ToArray();
    return Task.FromResult<IReadOnlyList<LangRuleCodeAction>>(actions);
}

Current local code actions replace one range in the active document. They are discarded if the document or caret changes while the action is being prepared. Only return safe edits for the diagnostic and range you received.

Development note: the LangRules assembly is loaded into a collectible AssemblyLoadContext that unloads on reload, so a rebuilt DLL picks up without a restart - but run the reload test (reload several times, watch memory) because a leaked context shows up as growth across reloads.

The contract

Kodo exposes the contract in the main assembly. Reference it from your project:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <EnableDynamicLoading>true</EnableDynamicLoading>
    <AssemblyName>LangRules</AssemblyName>
    <RootNamespace>MyLangKodoExtension</RootNamespace>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Kodo">
      <HintPath>..\..\Kodo\Kodo\Source\bin\Debug\net10.0\Kodo.dll</HintPath>
      <Private>false</Private>
    </Reference>
  </ItemGroup>
</Project>

TargetFramework must be net10.0, matching Kodo. Private=false stops a stale copy of Kodo.dll being shipped inside your package. Build Kodo once (dotnet build Kodo/Source/Kodo.csproj) so the reference resolves.

Discovery requirements

Kodo finds your provider by reflection. It must be:

  • not abstract
  • implement Kodo.ILangRulesProvider
  • instantiable with a public parameterless constructor (Activator.CreateInstance needs one)

The type itself does not need to be public - Kodo filters on IsAbstract and the interface only. If instantiation fails, the assembly loads and the provider is silently ignored (with a log entry).

Declaring capabilities

LangRulesCapability is a [Flags] enum. Declare exactly what you implement - a flag you claim but do not honour produces an empty or misleading command.

public LangRulesProviderInfo Info { get; } = new(
    "MyLang", "1.0.0",
    LangRulesCapability.Tokens |
    LangRulesCapability.Diagnostics |
    LangRulesCapability.Completions);

The flags are descriptive. Kodo derives its own capability set from the methods your assembly actually exposes, and uses that to decide which menu entries to offer. Declaring a flag you did not implement will not turn a feature on, and omitting one you did implement will not turn it off. Keep them accurate because they are reported to the UI, not because they gate anything.

Flag Enables You implement
Tokens Syntax coloring Tokenize
Symbols Declaration discovery (not an outline) AnalyzeSymbols
Diagnostics Syntax and workspace diagnostics AnalyzeSyntaxAsync or AnalyzeSyntax; optionally AnalyzeWorkspaceAsync
SemanticAnalysis Semantic errors AnalyzeSemanticsAsync or AnalyzeSemantics
Completions Suggestions GetCompletions
Definition Go to definition FindDefinition
References Find references FindReferences
Hover Information tooltip GetHover
SignatureHelp Parameter help GetSignatureHelp
CodeActions Quick fixes GetCodeActionsAsync or GetCodeActions
Formatting Document formatting FormatDocument
EmbeddedRegions Nested languages GetEmbeddedRegions

Every method on the interface has a default implementation that returns an empty value or null, so existing providers stay source-compatible. Kodo advertises capabilities from the methods your type actually overrides; Info.Capabilities is descriptive and should still match what you provide. None means no optional feature.

Add one flag at a time, and only after the matching method works on incomplete input.

Positions and ranges

  • All offsets are zero-based UTF-16 indices into the complete code string you are given.
  • Ranges are a Start plus a Length. Start + Length must stay within the string.
  • Line is zero-based.
  • Out-of-range values are filtered rather than crashing, but they make diagnostics silently disappear - clamp defensively.

The result types

new LangRuleToken(Kind, Text, Start, Length, Scope, Color)
new LangRuleSymbol(Name, Kind, Line, Start, Length, IsDeclaration)
new LangRuleDiagnostic(Start, Length, Message, Severity, Code, Source)
new LangRuleLocation(Name, Kind, Start, Length, IsDeclaration)
new LangRuleHover(Contents, Start, Length)
new LangRuleSignatureHelp(Label, Documentation, ActiveParameter)
new LangRuleCodeAction(Title, Kind, Start, Length, NewText, DiagnosticCode)
new LangRuleEmbeddedRegion(LanguageId, Start, Length)
Type Field notes
LangRuleToken Kind is a token class such as keyword; Color is a hex string.
LangRuleSymbol IsDeclaration marks the defining occurrence.
LangRuleDiagnostic Severity is user-facing ("error", "warning", "info", "hint"); Code is a stable machine-readable id a code action can match; Source identifies your provider.
LangRuleLocation IsDeclaration distinguishes the definition from uses.
LangRuleHover Put the signature before longer prose.
LangRuleSignatureHelp ActiveParameter is a zero-based index.
LangRuleCodeAction NewText replaces the returned range. DiagnosticCode links the action to a diagnostic.
LangRuleEmbeddedRegion Return only the inner region belonging to the embedded language.

A complete minimal provider

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Kodo;

namespace MyLangKodoExtension;

public sealed class MyLangProvider : ILangRulesProvider
{
    public LangRulesProviderInfo Info { get; } = new(
        "MyLang", "1.0.0",
        LangRulesCapability.Tokens |
        LangRulesCapability.Diagnostics |
        LangRulesCapability.Completions);

    public IReadOnlyList<LangRuleToken> Tokenize(string code) => Array.Empty<LangRuleToken>();

    public Task<IReadOnlyList<LangRuleDiagnostic>> AnalyzeSyntaxAsync(
        LangRulesDocumentContext document,
        CancellationToken cancellationToken)
    {
        var result = new List<LangRuleDiagnostic>();
        var open = 0;
        foreach (var c in document.Text)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (c == '(') open++;
            else if (c == ')') open--;
        }

        if (open > 0)
            result.Add(new LangRuleDiagnostic(
                document.Text.Length, 0,
                "A closing parenthesis is missing.", "error", "MY001", "MyLang"));

        return Task.FromResult<IReadOnlyList<LangRuleDiagnostic>>(result);
    }

    public IReadOnlyList<string> GetCompletions(string code, int offset, string prefix)
    {
        var words = new[] { "if", "else", "return", "print", "func" };
        var result = new List<string>();
        foreach (var w in words)
            if (w.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) result.Add(w);
        return result;
    }
}

prefix is what the user has already typed. Do not include it again in your results, and keep the list short.

Worked examples

Identifier scanning helper - most providers need this:

private static string WordAt(string code, int offset)
{
    offset = Math.Clamp(offset, 0, code.Length);
    var start = offset;
    while (start > 0 && (char.IsLetterOrDigit(code[start - 1]) || code[start - 1] == '_')) start--;
    var end = offset;
    while (end < code.Length && (char.IsLetterOrDigit(code[end]) || code[end] == '_')) end++;
    return code[start..end];
}

Definition and references:

public LangRuleLocation? FindDefinition(string code, int offset)
{
    if (WordAt(code, offset) != "print") return null;
    var start = code.IndexOf("print", StringComparison.Ordinal);
    return new LangRuleLocation("print", "function", start, 5, true);
}

public IReadOnlyList<LangRuleLocation> FindReferences(string code, int offset)
{
    var result = new List<LangRuleLocation>();
    for (var start = code.IndexOf("print", StringComparison.Ordinal);
         start >= 0;
         start = code.IndexOf("print", start + 1, StringComparison.Ordinal))
        result.Add(new LangRuleLocation("print", "function", start, 5, start == 0));
    return result;
}

Hover:

public LangRuleHover? GetHover(string code, int offset)
{
    if (WordAt(code, offset) != "print") return null;
    var start = code.LastIndexOf("print", Math.Clamp(offset, 0, code.Length), StringComparison.Ordinal);
    return new LangRuleHover("`print(value)` writes a value to the output.", start, 5);
}

Signature help:

public LangRuleSignatureHelp? GetSignatureHelp(string code, int offset)
{
    var upto = code[..Math.Clamp(offset, 0, code.Length)].TrimEnd();
    if (!upto.EndsWith("print(", StringComparison.Ordinal)) return null;
    return new LangRuleSignatureHelp("print(value)", "Writes value to the output.", 0);
}

For multiple parameters, scan backwards tracking parenthesis depth and count only top-level commas to compute ActiveParameter.

Code action:

public IReadOnlyList<LangRuleCodeAction> GetCodeActions(string code, int offset)
{
    if (!code.Contains("pritn", StringComparison.Ordinal)) return Array.Empty<LangRuleCodeAction>();
    var start = code.IndexOf("pritn", StringComparison.Ordinal);
    return new[] { new LangRuleCodeAction(
        "Change 'pritn' to 'print'", "quickfix", start, 5, "print", "MY001") };
}

Return only fixes that are safe and local. The Title is what the user sees.

Formatting - read this before you write it:

public string? FormatDocument(string code)
{
    // Preserve the document's existing line endings. Normalising CRLF to LF
    // here rewrites every line in the file and produces an enormous diff.
    var newline = code.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
    var lines = code.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n');
    return string.Join(newline, Array.ConvertAll(lines, l => l.TrimEnd()));
}

Formatting must be idempotent - running it twice should not keep changing the file. Real formatters need a parser: preserve comments and string contents, and never reflow inside a literal.

Embedded regions:

public IReadOnlyList<LangRuleEmbeddedRegion> GetEmbeddedRegions(string code)
{
    var start = code.IndexOf("<style>", StringComparison.Ordinal);
    var end = code.IndexOf("</style>", StringComparison.Ordinal);
    if (start < 0 || end <= start) return Array.Empty<LangRuleEmbeddedRegion>();
    start += "<style>".Length;
    return new[] { new LangRuleEmbeddedRegion("css", start, end - start) };
}

Return only the inner region. Never overlap regions or return an unterminated one.

The RecoveryAnalyzer convention

Shipped language packages commonly include a RecoveryAnalyzer class alongside the provider. It is not part of Kodo's API - it is a convention for the syntax recovery pass: cheap, dependency-free checks that keep the editor useful while code is half-written.

A recovery analyzer reports structural problems like unbalanced braces or brackets, unterminated strings, a missing semicolon after a directive, and unreachable code after a terminator.

internal static class RecoveryAnalyzer
{
    public static IReadOnlyList<LangRuleDiagnostic> Analyze(string code)
    {
        var result = new List<LangRuleDiagnostic>();
        var depth = 0;
        var offset = 0;
        foreach (var c in code)
        {
            if (c == '{') depth++;
            else if (c == '}') depth--;
            offset++;
        }
        if (depth > 0)
            result.Add(new LangRuleDiagnostic(
                Math.Max(0, code.Length - 1), 1,
                "Unclosed brace.", "error", "MY002", "MyLang"));
        return result;
    }
}

Call it from your AnalyzeSyntax. Keep it string- and comment-aware, or it will report errors inside string literals.

Maintaining a pre-2.1.0 extension

Before the typed contract existed, providers were a public static class LangRules discovered by name, with methods bound by reflection. Kodo still supports this, and several shipped packages use it. If you are maintaining one, the recognised method names are:

Tokenize, AnalyzeSymbols, GetCompletionsForPrefix, GetAllRegexes, GetColorMap, AnalyzeSyntax, AnalyzeSemantics, FindDefinition, FindReferences, GetHoverInfo, GetSignatureHelp, GetCodeActions, FormatDocument, GetEmbeddedRegions, FindDefinitionAt, FindReferencesAt, GetHoverInfoAt, GetCompletionsAt.

Note the naming difference from the typed interface: GetHoverInfo / GetHoverInfoAt rather than GetHover. GetAllRegexes and GetColorMap have no typed equivalent.

Kodo checks for a static LangRules class first and only falls back to ILangRulesProvider. If your assembly contains both, the static class wins and your typed provider is never called. For new work, ship only ILangRulesProvider.

Capabilities are derived automatically for the static-class form from which methods were found, so there is nothing to declare. With ILangRulesProvider you declare them yourself.

Verifying your provider with the conformance tool

Kodo-Extension-Template ships a dependency-free console tool at Tools/LangRules.Conformance that loads your compiled ILangRulesProvider and checks it against fixture files: syntax and semantic diagnostic ranges, workspace diagnostic URIs and ranges (including related locations), code action ranges, and cancellation of all four async analysis methods.

Build Kodo and your provider in Release first, then run it from the template root:

dotnet build ..\Kodo\Kodo\Source\Kodo.csproj -c Release
dotnet build Examples\Language-LangRules-Basic\LangRules.csproj -c Release
dotnet run --project Tools\LangRules.Conformance -- `
    Examples\Language-LangRules-Basic\LangRules.dll -- `
    Tools\LangRules.Conformance\Fixtures\first.myl `
    Tools\LangRules.Conformance\Fixtures\second.myl

For another provider, pass your DLL and fixture files for that language. The fixtures are treated as open documents in one workspace; their parent directory becomes the workspace root. Include empty, malformed, Unicode, and boundary cases when those are relevant to the language. The tool checks the provider contract, not Kodo's editor integration - still exercise rapid edits in Kodo and confirm stale results are discarded before installing your package.

Packaging a LangRules extension

mylang-kodo-extension/
β”œβ”€β”€ manifest.json
β”œβ”€β”€ language.json          ← still useful for the base profile
β”œβ”€β”€ LangRules.cs           ← ship your source alongside the DLL
β”œβ”€β”€ MyLangProvider.cs
β”œβ”€β”€ RecoveryAnalyzer.cs
β”œβ”€β”€ LangRules.dll
└── icon.png

Shipping the .cs files next to the DLL is the convention in published packages, and it makes the package reviewable. It costs nothing.

Compress-Archive -Path .\mylang-kodo-extension\* -DestinationPath .\mylang-1.0.0.zip
Rename-Item .\mylang-1.0.0.zip .\mylang-1.0.0.kox

Never include Kodo.dll in the package. Kodo provides it.

3. LSP

LSP is for established languages that have a real language server. You write configuration; the server does the parsing. This is by far the least code and the most correct option when it is available.

All fields live in manifest.json. The complete field and alias reference is in Kodo file format#lsp--lsps; this section covers choosing and testing one.

Minimal configuration

{
  "id": "mylang-lsp",
  "version": "1.0.0",
  "name": "MyLang",
  "type": "language",
  "author": "Your Name",
  "description": "MyLang support powered by a language server.",
  "extensions": [".myl"],
  "lsp": {
    "command": "mylang-language-server",
    "args": ["--stdio"],
    "languages": ["mylang"],
    "fileExtensions": [".myl"],
    "providerId": "mylang-ls",
    "displayName": "MyLang Language Server"
  }
}

That is enough for a server already on PATH. To let Kodo install it, add install metadata:

"lsp": {
  "command": "mylang-language-server",
  "languages": ["mylang"],
  "providerId": "mylang-ls",
  "installMethod": "npm",
  "packageName": "mylang-language-server",
  "allowSystem": true,
  "allowAutoInstall": true
}
installMethod Kodo runs Use for
npm npm install --prefix <staging> <packageName> with --ignore-scripts, then promoted into Kodo's Lsp folder Most JS/TS servers
dotnet dotnet tool install --global <packageName> .NET servers
download fetches downloadUrl directly, unpacking .zip/.tar.gz Self-contained artifacts
github like download, but resolves GitHub asset/release URLs Servers hosted on GitHub releases
manual nothing; Kodo never installs it Toolchains the user installs by hand
(omit) nothing; expects the server on PATH System-provided servers

npm installs are not global - Kodo stages them into a private prefix and promotes the result into %LocalAppData%\Kodo\Lsp, so nothing is written to a machine-wide npm root.

allowSystem: true lets Kodo use a server already installed. allowAutoInstall: true lets Kodo install without prompting. Add sha256 to verify a download install.

version does not pin the install. It is not read by the npm or dotnet installers; it is only used when checking whether an already-installed server satisfies a minimum. To pin an npm or dotnet server, put the version in packageName (for example typescript-language-server@5.0.0) or gate it with allowAutoInstall: false and ship your own wrapper.

Cross-platform commands

One command value is used on every platform:

  • Prefer an extensionless name: mylang-language-server, not mylang-language-server.exe.
  • .cmd and .bat suffixes are stripped when spawning on Linux. .exe is stripped during the PATH lookup, so an extensionless binary next to a .exe of the same name resolves correctly.
  • Kodo does not rewrite python β†’ python3 or powershell β†’ pwsh for language servers. That mapping applies to a compiler's run/build commands and to externalTools, but a server's command is launched as written. If your server is a script, name the interpreter explicitly (command: "python3", and pass its arguments via args). Note: runtimeArgs and mainClass are not read from manifest.json - only args (alias arguments) supplies server arguments.

If a server genuinely needs different binaries per OS, publish two .kox files and gate them with the marketplace os field (["windows"] and ["linux"]). Do not try to encode conditionals in command.

Several servers, or several file families

Use lsps when one package covers languages with different servers, or one language whose file types are handled by different servers:

"lsps": [
  {
    "command": "html-language-server",
    "languages": ["html"],
    "fileExtensions": [".html", ".htm"]
  },
  {
    "command": "css-language-server",
    "languages": ["css"],
    "fileExtensions": [".css", ".scss"]
  }
]

Each entry needs its own command. Top-level extensions act as a fallback when no entry claims a file. languageServers is accepted as an alias for lsps; lsp (singular) is the older single-server form and both are supported.

Workspace roots

Servers expect a workspace root, not a bare file path. Give Kodo markers to search for:

"rootMarkers": ["package.json", "tsconfig.json", ".git"]

Kodo walks up from the file looking for the first directory containing one. If none is found it falls back to the enclosing open folder, then the file's own directory.

Feature mapping

Advertise each capability during initialize and implement the matching request. Kodo maps them as follows:

Kodo feature LSP request / notification
Completion textDocument/completion
Hover textDocument/hover
Diagnostics textDocument/publishDiagnostics (after didOpen / didChange)
Go to definition textDocument/definition
Type definition textDocument/typeDefinition
Implementations textDocument/implementation
Find references textDocument/references
Rename textDocument/rename
Formatting textDocument/formatting
Code actions textDocument/codeAction
Signature help textDocument/signatureHelp
Document outline textDocument/documentSymbol
Folding textDocument/foldingRange
Semantic tokens textDocument/semanticTokens/full
Inlay hints textDocument/inlayHint
Document highlights textDocument/documentHighlight

Rules your server must follow

These are not stylistic. Kodo enforces them.

  • Use the negotiated position encoding. Kodo offers utf-8, utf-32, and utf-16 during initialize and uses whichever your server picks (defaulting to utf-16). Use the negotiated encoding for all positions - not bytes, and not UTF-16 if your server picked UTF-8.
  • Clear diagnostics by publishing an empty array. Stale errors linger otherwise.
  • Never return an edit computed from a stale document version. Kodo rejects formatting and rename results if the document changed while the request was in flight, and the user sees nothing happen.
  • Honour cancellation. Kodo sends $/cancelRequest; ignoring it causes flicker.
  • Return null or an empty result when a feature does not apply. Do not invent a plausible answer.
  • Format defensively. Return the smallest safe edit; do not reflow the whole document.

Testing an LSP extension

  1. Run the command manually first. mylang-language-server --stdio, then send it a Content-Length framed initialize request. If it does not start here, it will not start in Kodo.
  2. Install the package and open a file of the target type.
  3. Confirm Kodo reports the server as running, and that the language id sent in didOpen matches what your server expects. A mismatch is the most common cause of "starts but has no features".
  4. Check diagnostics appear, then completion, then hover.
  5. Only then add advanced features.

If the server starts but nothing works, the language id and workspace root are the first two things to check. Kodo traces the whole exchange to its own log when verbose logging is enabled; the tracing lives in Kodo's internal KodoDiagnostics.LogDebug, which is internal and so is not callable from your extension. You get the effect by turning verbose logging on and reading Kodo's log file.


Troubleshooting language extensions

Symptom Check first Then check
Language never appears in the list manifest.json is at the package root type is language; extensions includes the leading dot
Colors are wrong or absent language.json is valid JSON and beside the manifest colorTokens keys are spelled correctly; Kodo is not falling back to defaults
One file type is colored, another is not the profile's extensions array a non-empty array scopes the profile; empty merges it
LangRules features missing plugin names your DLL, not languagePlugin the type is non-abstract and has a public parameterless constructor (public on the type is not required); the method is actually overridden rather than left as the interface default
A feature is offered but returns nothing the method is implemented, not just declared ranges are within the document
LangRules changes have no effect reload the package (collectible context) the new DLL actually replaced the old one - same version in the manifest means the old build keeps running
Signature help never appears - GetSignatureHelp has no UI entry point in Kodo; signature help is LSP-only
Document outline is empty - the outline is LSP-only; AnalyzeSymbols feeds declaration discovery, not an outline
language.json edits do not appear use the Extensions page refresh, or restart the folder watcher ignores in-place edits and ignores language.json by name
LSP starts but has no features the language id in languages fileExtensions; workspace root via rootMarkers
LSP never starts run the command manually allowSystem; the server is installed under %LocalAppData% for managed installs
The wrong theme colors apply to dialogs not applicable theme and accent are read from settings, not from your package
Plugin listed but does nothing plugin DLL name matches exactly target framework is net10.0; the DLL loads as a plugin too and may need IKodoPlugin

Related guides

Clone this wiki locally