API Reference

Reference documentation for the Polyfont Rust crates. All crates are part of the same workspace and share a common version.

polyfont-core

Core types, traits, and the scope-match engine. This crate defines the fundamental data structures shared by all other crates.

FontWeight

Enum representing CSS-style font weights.

pub enum FontWeight {
    Thin        = 100,
    ExtraLight  = 200,
    Light       = 300,
    Regular     = 400,  // default
    Medium      = 500,
    SemiBold    = 600,
    Bold        = 700,
    ExtraBold   = 800,
    Black       = 900,
}

Implements: Debug, Default (Regular), Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Display.

Serialized as kebab-case strings: "thin", "extra-light", "light", "regular", "medium", "semi-bold", "bold", "extra-bold", "black".

FontStyle

Enum representing font styles.

pub enum FontStyle {
    Normal,   // default
    Italic,
    Oblique,
}

Implements: Debug, Default (Normal), Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Display.

FontSpec

Complete font specification for a rule or default.

pub struct FontSpec {
    pub family: String,
    pub fallbacks: Vec<String>,
    pub weight: FontWeight,
    pub style: FontStyle,
    pub size: Option<f32>,
}
FieldTypeDescription
familyStringPrimary font family name.
fallbacksVec<String>Fallback font families in priority order. Defaults to empty.
weightFontWeightFont weight. Defaults to Regular.
styleFontStyleFont style. Defaults to Normal.
sizeOption<f32>Font size in points. None inherits from editor.

Methods:

  • FontSpec::default_font(family: &str) -> Self -- creates a FontSpec with only the family set and all other fields at defaults.

FontRule

A single scope-to-font mapping rule.

pub struct FontRule {
    pub scope: String,
    pub font: FontSpec,
}
FieldTypeDescription
scopeStringTextMate scope selector pattern.
fontFontSpecFont specification for this scope.

Methods:

  • FontRule::specificity(&self) -> usize -- returns the number of dot-separated segments in the scope. Used for specificity-based resolution.

FontAssignment

The result of resolving a token against the rule set.

pub struct FontAssignment {
    pub scope: String,
    pub font: FontSpec,
    pub specificity: usize,
    pub is_active: bool,
}
FieldTypeDescription
scopeStringThe token's scope that was matched.
fontFontSpecThe resolved font specification.
specificityusizeSpecificity of the winning rule.
is_activeboolWhether this assignment is currently active.

TokenInfo

Represents a single syntax token from the editor.

pub struct TokenInfo {
    pub text: String,
    pub range: Range,
    pub scope: String,
    pub modifiers: Vec<String>,
}
FieldTypeDescription
textStringThe literal text of the token.
rangeRangeStart and end position in the document.
scopeStringTextMate scope (e.g., "keyword.control").
modifiersVec<String>Semantic token modifiers.

Position and Range

pub struct Position {
    pub line: u32,
    pub column: u32,
}

pub struct Range {
    pub start: Position,
    pub end: Position,
}

TokenCollection

A collection of tokens for a single document.

pub struct TokenCollection {
    pub uri: String,
    pub language: String,
    pub tokens: Vec<TokenInfo>,
}

PolyfontEngine (trait)

The core engine trait. Implemented by ScopeMatchEngine.

pub trait PolyfontEngine: Send + Sync {
    fn add_rule(&mut self, rule: FontRule);
    fn remove_rule(&mut self, scope: &str);
    fn rules(&self) -> &[FontRule];
    fn resolve_token(&self, token: &TokenInfo) -> Option<FontAssignment>;
    fn resolve_all(&self, tokens: &[TokenInfo]) -> Vec<Option<FontAssignment>>;
    fn clear(&mut self);
}
MethodDescription
add_ruleAdd a font rule. Rules are re-sorted by specificity after insertion.
remove_ruleRemove a rule by its exact scope string.
rulesGet a slice of all current rules, sorted by specificity (descending).
resolve_tokenResolve a single token to its font assignment. Returns None if no rule matches.
resolve_allResolve a batch of tokens. Returns a parallel Vec<Option<FontAssignment>>.
clearRemove all rules.

ScopeMatchEngine

The default implementation of PolyfontEngine. Rules are stored sorted by specificity (descending) and the first matching rule wins.

pub struct ScopeMatchEngine {
    // rules sorted by specificity descending
}

impl ScopeMatchEngine {
    pub const fn new() -> Self;
    pub fn from_rules(rules: Vec<FontRule>) -> Self;
    pub fn scope_matches(scope: &str, pattern: &str) -> bool;
}

scope_matches implements hierarchical matching: "keyword" matches "keyword", "keyword.control", "keyword.operator", etc. The pattern "*" matches any scope.

PolyfontError

pub enum PolyfontError {
    Config(String),
    FontNotFound(String),
    InvalidScope(String),
    Io(std::io::Error),
    Parse(String),
}

polyfont-config

Configuration file parsing, validation, and merging. Handles .polyfont.toml discovery, loading, and hierarchical config merging.

PolyfontConfig

The root configuration type.

pub struct PolyfontConfig {
    pub version: u32,
    pub default: Option<DefaultFontConfig>,
    pub rules: Vec<RuleConfig>,
}

Methods:

  • validate(&self) -> Result<(), ConfigError> -- checks version is 1, default family is non-empty, all rule scopes and families are non-empty.
  • to_rules(&self) -> Vec<FontRule> -- converts config rules to FontRule objects. Appends a catchall * rule from the default section if present.
  • PolyfontConfig::merge(base, overlay) -> Self -- merges two configs. The overlay's rules replace the base's rules. The overlay's default replaces the base's default if present.

DefaultFontConfig

pub struct DefaultFontConfig {
    pub family: String,
    pub fallbacks: Vec<String>,
    pub weight: FontWeight,
    pub style: FontStyle,
    pub size: Option<f32>,
}

RuleConfig

pub struct RuleConfig {
    pub scope: String,
    pub font: FontConfig,
}

FontConfig

pub struct FontConfig {
    pub family: String,
    pub fallbacks: Vec<String>,
    pub weight: FontWeight,
    pub style: FontStyle,
    pub size: Option<f32>,
}

ConfigLoader

Static methods for discovering and loading config files.

pub struct ConfigLoader;

impl ConfigLoader {
    pub fn load_from_path(path: &Path) -> Result<PolyfontConfig, ConfigError>;
    pub fn load_from_dir(start_dir: &Path) -> Result<PolyfontConfig, ConfigError>;
    pub fn find_config(start_dir: &Path) -> Option<PathBuf>;
    pub fn load_merged(start_dir: &Path) -> Result<PolyfontConfig, ConfigError>;
}
MethodDescription
load_from_pathLoad and validate a config from an explicit file path.
load_from_dirSearch upward from start_dir for .polyfont.toml and load the first one found.
find_configSearch upward for .polyfont.toml. Returns the path or None.
load_mergedFind all .polyfont.toml files from ancestor dirs to the current directory. Load and merge them in order (outermost first), so the nearest config takes precedence.

ConfigError

pub enum ConfigError {
    UnsupportedVersion { found: u32, expected: u32 },
    Validation(String),
    Io(std::io::Error),
    Parse(toml::de::Error),
    NotFound(PathBuf),
}

polyfont-scope

TextMate scope matching, specificity resolution, and scope tree data structures. Extends the basic matching in polyfont-core with support for wildcards, negation, and comma-separated selectors.

ScopePattern

A single scope pattern, optionally negated.

pub struct ScopePattern { /* private fields */ }

impl ScopePattern {
    pub fn parse(pattern: &str) -> Result<Self, ScopeError>;
    pub fn matches_scope(&self, scope: &str) -> bool;
    pub fn specificity(&self) -> usize;
}

Supports: literal segments ("entity.name"), wildcard segments ("entity.*"), negation prefix ("-keyword.operator").

ScopeSelector

A comma-separated list of scope patterns (OR logic). Negative patterns exclude matches.

pub struct ScopeSelector { /* private fields */ }

impl ScopeSelector {
    pub fn parse(selector: &str) -> Result<Self, ScopeError>;
    pub fn matches(&self, scope: &str) -> bool;
    pub fn specificity(&self) -> usize;
}

Example: "keyword,-keyword.operator" matches keyword.control but not keyword.operator.

ScopeMatcher

Convenience functions for one-off matching.

pub struct ScopeMatcher;

impl ScopeMatcher {
    pub fn matches(scope: &str, selector: &str) -> Result<bool, ScopeError>;
    pub fn matches_any(scope: &str, selectors: &[&str]) -> Result<bool, ScopeError>;
}

ScopeResolver

Resolves scopes to font assignments using specificity and insertion-order tiebreaking.

pub struct ScopeResolver { /* private fields */ }

impl ScopeResolver {
    pub const fn new() -> Self;
    pub fn from_rules(rules: Vec<FontRule>) -> Self;
    pub fn add_rule(&mut self, rule: FontRule);
    pub fn resolve(&self, scope: &str) -> Option<ResolvedScope>;
    pub fn resolve_all<'a, I>(&self, scopes: I) -> Vec<Option<ResolvedScope>>;
    pub fn clear(&mut self);
    pub const fn rule_count(&self) -> usize;
}

ResolvedScope

pub struct ResolvedScope {
    pub assignment: FontAssignment,
    pub rule_index: usize,
}

ScopeTree

A trie data structure for efficient scope prefix queries.

pub struct ScopeTree { /* private fields */ }

impl ScopeTree {
    pub fn new() -> Self;
    pub fn insert(&mut self, scope: &str);
    pub fn contains(&self, scope: &str) -> bool;
    pub fn has_prefix(&self, prefix: &str) -> bool;
    pub fn query_prefix(&self, prefix: &str) -> Vec<String>;
    pub fn len(&self) -> usize;
    pub fn is_empty(&self) -> bool;
}

ScopeError

pub enum ScopeError {
    EmptyPattern,
    InvalidPattern(String),
}

Scope Constants

Commonly used scope strings as constants:

pub const SCOPE_KEYWORD:     &str = "keyword";
pub const SCOPE_COMMENT:     &str = "comment";
pub const SCOPE_STRING:      &str = "string";
pub const SCOPE_FUNCTION:    &str = "entity.name.function";
pub const SCOPE_VARIABLE:    &str = "variable";
pub const SCOPE_CONSTANT:    &str = "constant";
pub const SCOPE_TYPE:        &str = "entity.name.type";
pub const SCOPE_NUMBER:      &str = "constant.numeric";
pub const SCOPE_OPERATOR:    &str = "keyword.operator";
pub const SCOPE_PUNCTUATION: &str = "punctuation";
pub const SCOPE_TAG:         &str = "entity.name.tag";
pub const SCOPE_ATTRIBUTE:   &str = "entity.other.attribute-name";

polyfont-parse

Tree-sitter-based token parser with per-language grammars and a naive fallback for unsupported languages.

TokenParser

pub struct TokenParser { /* private fields */ }

impl TokenParser {
    pub fn new() -> Self;
    pub fn parse_tokens(
        &self,
        text: &str,
        language_id: &str,
        offset_encoding: OffsetEncoding,
    ) -> Result<Vec<TokenInfo>, ParseError>;
}

Tries tree-sitter parsing first. Falls back to naive line-prefix classification when no grammar is available for the language. Language grammars are feature-gated (e.g., --features rust).

Supported Languages

Feature-gated grammars: rust, c, cpp, go, python, javascript, typescript, java, ruby, html. Default features are empty -- no grammars are included unless explicitly enabled.

OffsetEncoding

pub enum OffsetEncoding {
    Utf8,
    Utf16,
}

ParseError

pub enum ParseError {
    UnsupportedLanguage(String),
    ParseFailed { language: String, message: String },
}

polyfont-fonts

Cross-platform font discovery and management. Provides a trait-based abstraction over platform-specific font enumeration APIs.

FontDiscovery (trait)

pub trait FontDiscovery: Send + Sync {
    fn list_families(&self) -> Result<Vec<String>, FontError>;
    fn find_family(&self, name: &str) -> Result<bool, FontError>;
    fn font_path(&self, name: &str) -> Option<PathBuf>;
}

Platform Implementations

StructPlatformMethod
FcListDiscoveryLinuxfc-list via std::process::Command
MacOsDiscoverymacOSsystem_profiler SPFontsDataType
WindowsDiscoveryWindowsPowerShell Get-ChildItem on font directories
FallbackDiscoveryAllReturns empty list

FontScanner

pub struct FontScanner { /* private fields */ }

impl FontScanner {
    pub fn new() -> Self;
    pub fn with_discovery(discovery: Box<dyn FontDiscovery>) -> Self;
    pub fn is_available(&self, family: &str) -> bool;
    pub fn available_families(&self) -> Vec<String>;
    pub fn check_config(&self, families: &[&str]) -> FontCheckResult;
}

create_discovery()

Auto-selects the platform-appropriate discovery implementation:

pub fn create_discovery() -> Box<dyn FontDiscovery>;

FontCheckResult

pub struct FontCheckResult {
    pub available: Vec<String>,
    pub missing: Vec<String>,
}

FontError

pub enum FontError {
    DiscoveryFailed(String),
    CommandFailed(String),
    ParseError,
}

polyfont-themes

Theme import, export, and registry. Supports VSCode/TextMate JSON themes and provides 5 built-in themes.

ThemeImporter

pub struct ThemeImporter;

impl ThemeImporter {
    pub fn import_vscode(json: &str) -> Result<PolyfontConfig, ThemeError>;
    pub fn import_textmate(json: &str) -> Result<PolyfontConfig, ThemeError>;
}

Imports VSCode theme JSON files. Extracts fontStyle from token colors and maps to FontWeight/FontStyle. Font families are assigned via a configurable mapping with prefix-match fallback.

ThemeExporter

pub struct ThemeExporter;

impl ThemeExporter {
    pub fn export_config(config: &PolyfontConfig) -> Result<String, ThemeError>;
    pub fn export_vscode(config: &PolyfontConfig) -> Result<String, ThemeError>;
}

ThemeRegistry

pub struct ThemeRegistry;

impl ThemeRegistry {
    pub fn list() -> Vec<&'static str>;
    pub fn get(name: &str) -> Option<&'static BuiltinTheme>;
}

Built-in Themes

NameDescriptionRules
monaspaceMonaspace font family across scopes10+
serif-monoSerif for comments, mono for code6+
weight-differentiatedSame family, different weights6+
minimalOnly 4 scope categories4
maximal17+ distinct scope rules17+

ThemeError

pub enum ThemeError {
    InvalidJson(String),
    MissingField(String),
    InvalidScope(String),
    ImportFailed(String),
    ExportFailed(String),
}

polyfont-lsp

Language Server Protocol server for editor integration. Built on tower-lsp. Provides real-time font assignment notifications to connected editors.

PolyfontLanguageServer

The LSP server implementation.

pub struct PolyfontLanguageServer { /* private fields */ }

impl PolyfontLanguageServer {
    pub fn new(client: Client) -> Self;
    pub fn build_service() -> (LspService<Self>, ClientSocket);
}

LSP Protocol

Capabilities

  • Text document synchronization: full
  • Custom method: polyfont/requestFontAssignments

Custom notification: polyfont/fontAssignments

Sent to the client when a document is opened or changed.

pub struct FontAssignmentNotification {
    pub uri: String,
    pub assignments: Vec<FontAssignmentEntry>,
}

FontAssignmentEntry

pub struct FontAssignmentEntry {
    pub scope: String,
    pub range: LspRange,
    pub font: FontInfo,
}

FontInfo

pub struct FontInfo {
    pub family: String,
    pub fallbacks: Vec<String>,
    pub weight: String,
    pub style: String,
}

weight and style are omitted from serialization when they are the defaults ("regular" and "normal"). fallbacks is omitted when empty.

Custom request: polyfont/requestFontAssignments

Request font assignments for a specific document URI.

Params:

{ "uri": "file:///path/to/document.rs" }

Returns: FontAssignmentNotification | null

LSP types

pub struct LspRange {
    pub start: LspPosition,
    pub end: LspPosition,
}

pub struct LspPosition {
    pub line: u32,
    pub character: u32,
}

LSP Server Binary

The polyfont-lsp crate produces a binary that runs the LSP server over stdio:

cargo build --release -p polyfont-lsp
./target/release/polyfont-lsp

Configure your editor to start polyfont-lsp as a language server. The server will search for .polyfont.toml in the workspace root.

Configuration Reloading

The LSP server reloads the config on didChangeConfiguration notifications. After reloading, it re-publishes font assignments for all open documents.

polyfont-cli

Command-line interface for polyfont. Provides editor config generation, font checking, and theme management.

Usage

polyfont [OPTIONS] <COMMAND>

Commands:
  check              Verify font availability and config validity
  vscode             Generate VSCode textMateRules settings
  neovim             Generate Neovim highlight group Lua code
  kitty              Generate Kitty symbol_map configuration
  dump               Dump current config as JSON
  font               Font management subcommands
  theme              Theme management subcommands
  help               Print help

Font subcommands:
  polyfont font list                 List all available font families
  polyfont font check <family>...   Check if fonts are installed

Theme subcommands:
  polyfont theme list                List built-in themes
  polyfont theme show <name>        Show theme details
  polyfont theme apply <name>       Write theme to .polyfont.toml

Options

FlagDescription
-c, --config <path>Path to .polyfont.toml (default: auto-discover)
-o, --output <path>Output file path (default: stdout)
-v, --verboseEnable verbose logging