API Reference
Public API
Highlights.Highlight — Type
HighlightDisplayable syntax-highlighted code. Unlike highlight() which returns a String, Highlight objects integrate with Julia's display system via show methods.
Example
code = Highlight("println(1)", :julia, "Dracula")
display(code) # ANSI in terminal
display(MIME"text/html"(), code) # HTML outputConstructors
Highlight(source, language, theme; kwargs...)Arguments and keyword arguments match highlight.
Highlights.Theme — Type
ThemeRepresents a color theme with 16 ANSI colors, special colors, and optional per-capture text styling (bold, italic, underline).
Fields
name::String: Theme namecolors::Dict{Int,String}: Maps color index (1-16) to hex color stringbackground::String: Background color (hex)foreground::String: Default text color (hex)styles::Dict{String,Vector{Symbol}}: Maps capture name (e.g."comment") to a list of style flags. Valid symbols::bold,:italic,:underline. Lookup uses hierarchical fallback: setting"keyword"covers"keyword.return".
Custom Themes
Create custom themes by deriving from existing themes:
# Override specific colors
Theme("Dracula", colors = Dict(2 => "#ff0000"))
# Change background
Theme("Nord", background = "#1a1a1a")
# Add styling (bare Symbol or Vector accepted)
Theme("Dracula", styles = Dict(
"comment" => :italic,
"keyword" => :bold,
"function" => [:bold, :italic],
"type" => :underline,
))
# Give it a new name
Theme("Dracula", name = "MyDracula", colors = Dict(2 => "#ff0000"))
# Chain derivations
base = Theme("Dracula", background = "#1a1a1a")
custom = Theme(base, colors = Dict(3 => "#00ff00"))Style merge semantics
Derived-theme styles override the base per-capture (last-wins), matching colors. To remove a base style, set the capture to Symbol[].
Highlights.highlight — Method
highlight(source::AbstractString, language, theme; transform=default_transform) -> String
highlight(mime, source::AbstractString, language, theme; transform=default_transform) -> String
highlight(io::IO, mime, source::AbstractString, language, theme; transform=default_transform)Highlight source code using tree-sitter and a color theme.
Arguments
source: Source code to highlightlanguage: Language specifier - JLL module, Symbol, or String (e.g.,:julia,"python")theme: Theme name (String) orThemeobject (seeavailable_themes(), custom themes below)mime: Output format as MIME type or string (default:MIME("text/ansi"))MIME("text/ansi")or"text/ansi"- Terminal with 24-bit true colorMIME("text/html")or"text/html"- HTML with inline stylesMIME("text/latex")or"text/latex"- LaTeX with color commandsMIME("text/plain")or"text/plain"- Debug format with capture names
transform: Function to wrap tokens (seedefault_transform)
Language Resolution
Languages are case-insensitive and support common aliases:
js→javascriptts→typescriptpy→pythonrb→rubyyml→yamlrs→rustcs→c_sharpc++,cxx→cppsh,shell,zsh→bashjl→julia
If a language is not found, similar languages are suggested based on edit distance. Use available_languages() to list all installable language grammars.
Example
using Highlights
code = """
function hello(name)
println("Hello, $name!")
end
"""
# Default ANSI output for terminal
println(highlight(code, :julia, "Dracula"))
# HTML output
html = highlight(MIME("text/html"), code, :julia, "Nord")
# Using string MIME
html = highlight("text/html", code, "julia", "Nord")
# Custom theme derived from Dracula
custom = Theme("Dracula", colors = Dict(2 => "#ff0000"))
println(highlight(code, :julia, custom))Highlights.stylesheet — Method
stylesheet(theme; classprefix="hl") -> String
stylesheet(mime, theme; classprefix="hl") -> String
stylesheet(io::IO, mime, theme; classprefix="hl")Generate a stylesheet for class-based syntax highlighting. theme is a built-in theme name (String) or a Theme object — useful when the theme carries custom styling.
Arguments
classprefix: Prefix for CSS classes/LaTeX commands (default "hl")
Supported MIME types
MIME"text/css"- Raw CSS rulesMIME"text/html"- CSS wrapped in<style>tagsMIME"text/latex"- LaTeX\newcommanddefinitions
Style modifiers
If the theme uses per-capture styling (:bold, :italic, :underline), matching modifier classes/commands are emitted alongside color rules:
- CSS:
.hl-bold,.hl-italic,.hl-underline - LaTeX:
\HLB,\HLI,\HLU(and\usepackage[normalem]{ulem}if any capture uses underline)
Modifiers are emitted only if the theme actually uses them.
Example
css = stylesheet("Dracula")
html_style = stylesheet(MIME("text/html"), "Nord")
# Custom prefix
css = stylesheet("Dracula"; classprefix="syntax")
# → pre.syntax { ... }
# → .syntax-c1 { ... }
# Use with class-based HTML output
code_html = highlight("text/html", code, :julia, "Dracula"; stylesheet=true)
full_html = stylesheet("text/html", "Dracula") * code_html
# Styled theme — pass the Theme directly so modifier rules get emitted
my_theme = Theme("Dracula", styles = Dict("comment" => :italic))
stylesheet(MIME("text/css"), my_theme)Internal API
Highlights.CodeSegment — Type
CodeSegmentA code block to be syntax-highlighted with TreeSitter.
Fields
text::String: Source codelanguage::Symbol: Language to highlight as (e.g.,:julia,:bash)line_prefixes::Vector{Tuple{String,Int}}: (prefix, color) for each line (e.g., continuation prompts)
Highlights.HighlightToken — Type
HighlightTokenRepresents a syntax-highlighted token with position and AST information.
Fields
text: The token textcapture: Tree-sitter capture name (e.g., "function.call")byte_range: Start and end byte positions in sourcenode: Original TreeSitter.Node for AST navigation (Nothing for synthetic tokens)
Highlights.ReplConfig — Type
ReplConfigConfiguration for a REPL preprocessor.
Fields
modes::Vector{ReplMode}: Prompt modes (checked in order)continuation::Union{Regex,Nothing}: Pattern for continuation lines (must capture code)continuation_prompt::String: Prompt to display for continuation lines
Highlights.ReplMode — Type
ReplModeConfiguration for a REPL prompt mode.
Fields
pattern::Regex: Pattern to match the prompt (must capture the code after prompt)prompt::String: The prompt string to displaycolor::Int: Color index for the promptlanguage::Union{Symbol,Nothing}: Language for syntax highlighting, or nothing for plain text
Highlights.Segment — Type
SegmentAbstract type for preprocessor output segments.
Highlights.StyledSegment — Type
StyledSegmentA text block with a single color (no syntax highlighting).
Fields
text::String: Text contentcolor::Int: Theme color index (1-16), or 0 for foreground
Highlights.ansi_color_from_hex — Method
ansi_color_from_hex(hex::AbstractString; background::Bool=false) -> StringGenerate ANSI 24-bit true color escape sequence from hex color string.
Highlights.ansi_color_rgb — Method
ansi_color_rgb(r::Int, g::Int, b::Int; background::Bool=false) -> StringGenerate ANSI 24-bit true color escape sequence.
Highlights.ansi_reset — Method
ansi_reset() -> StringReturn ANSI reset escape sequence to clear all formatting.
Highlights.ansi_styles — Method
ansi_styles(styles) -> StringBuild the ANSI SGR escape sequence for a list of style flags (:bold, :italic, :underline). Returns an empty string if styles is empty.
Highlights.available_language_jlls — Method
available_language_jlls() -> Vector{String}Return all treesitter*_jll packages available in registries.
Highlights.available_languages — Method
available_languages() -> Vector{String}Return sorted list of language names available in registries.
Use this to discover installable grammar packages. Each name corresponds to a tree_sitter_<name>_jll package that can be installed via Pkg.add.
See also: available_themes
Highlights.available_themes — Method
available_themes() -> Vector{String}Return a sorted list of all available theme names.
Highlights.clear_theme_cache! — Method
clear_theme_cache!()Clear the theme cache.
Highlights.color_distance — Method
color_distance(c1::AbstractString, c2::AbstractString) -> Float64Compute perceptual distance between two hex colors.
Highlights.deduplicate_tokens — Method
deduplicate_tokens(tokens::Vector{HighlightToken}, priorities::Dict) -> Vector{HighlightToken}Layer overlapping tokens, preferring more specific (shorter) tokens. For identical ranges, highest priority wins.
Highlights.default_capture_colors — Method
default_capture_colors() -> Dict{String,Int}Default mapping from tree-sitter capture names to ANSI color indices (1-16).
Highlights.default_capture_priorities — Method
default_capture_priorities() -> Dict{String,Int}Default priority mapping for capture names. Higher = wins when overlapping.
Highlights.default_transform — Method
default_transform(io::IO, mime::MIME, token::HighlightToken, entering::Bool, source::AbstractString, language::Symbol)No-op transform function. Users can provide a custom function to wrap tokens.
The transform is called twice per token:
entering=truebefore the token is rendered (write opening wrapper)entering=falseafter the token is rendered (write closing wrapper)
Arguments
io: Output stream to write wrapper contentmime: Output format MIME typetoken: The token with.text,.capture,.byte_range,.nodeentering: true before rendering, false aftersource: Full source code (for slicing AST nodes)language: Language being highlighted (e.g.,:julia,:bash)
Example: Language-aware linking
function link_docs(io::IO, ::MIME"text/html", token, entering::Bool, source, language)
# Only link in Julia code
language == :julia || return
if token.capture == "function.call" && entering
print(io, "<a href="/docs/$(token.text)">")
elseif token.capture == "function.call" && !entering
print(io, "</a>")
end
end
link_docs(::IO, ::MIME, t, e, s, l) = nothing
highlight("text/html", code, :julia, "Dracula"; transform=link_docs)Highlights.escape_html — Method
escape_html(io::IO, s::AbstractString)
escape_html(s::AbstractString) -> StringEscape HTML special characters.
Highlights.escape_latex — Method
escape_latex(io::IO, s::AbstractString)
escape_latex(s::AbstractString) -> StringEscape LaTeX special characters.
Highlights.extract_language_name — Method
extract_language_name(pkg::String) -> StringExtract language name from JLL package name (treesitterX_jll -> X).
Highlights.format — Method
format(io::IO, ::MIME"text/ansi", tokens, source, theme, language;
mapping=default_capture_colors(), transform=default_transform, wrap=true,
line_prefixes=Tuple{String,Int}[])Format tokens with ANSI color codes for terminal output. The wrap parameter is accepted for API consistency but ignored (ANSI has no wrapper).
Highlights.format — Method
format(io::IO, ::MIME"text/html", tokens, source, theme, language;
mapping=default_capture_colors(), transform=default_transform, wrap=true,
stylesheet=false, classprefix="hl", line_prefixes=Tuple{String,Int}[])Format tokens as HTML.
Set stylesheet=false (default) for inline styles: <span style="color: #hex">. Set stylesheet=true for CSS classes: <span class="hl-c1"> (use with stylesheet()). Set classprefix to customize the CSS class prefix (default "hl"). Set wrap=false to skip the <pre> wrapper (for preprocessed segments).
Highlights.format — Method
format(io::IO, ::MIME"text/latex", tokens, source, theme, language;
mapping=default_capture_colors(), transform=default_transform, wrap=true,
stylesheet=false, classprefix="hl", line_prefixes=Tuple{String,Int}[])Format tokens as LaTeX with color commands.
Set stylesheet=false (default) for inline colors: \textcolor[RGB]{...}{text}. Set stylesheet=true for stylesheet commands: \HLC1{text} (use with stylesheet()). Set classprefix to customize the command prefix (default "hl", commands become \HLC1). Set wrap=false to skip the lstlisting wrapper (for preprocessed segments).
If the theme uses :underline styling, the ulem package must be loaded in the document preamble: \usepackage[normalem]{ulem}. The stylesheet() output for MIME("text/latex") includes this automatically.
Highlights.format — Method
format(io::IO, ::MIME"text/plain", tokens, source, theme, language;
transform=default_transform, line_prefixes=Tuple{String,Int}[])Format tokens as plain text with capture names in brackets. Useful for debugging highlighting queries.
Highlights.format — Method
format(io::IO, ::MIME"text/typst", tokens, source, theme, language;
mapping=default_capture_colors(), transform=default_transform, wrap=true,
line_prefixes=Tuple{String,Int}[])Format tokens as Typst markup with colored text. Set wrap=false to skip the block wrapper (for preprocessed segments).
Highlights.format_styled — Method
format_styled(io::IO, ::MIME"text/ansi", text::AbstractString, color::Int, theme::Theme)Output text with a single color for ANSI terminal. Color 0 uses theme foreground, 1-16 use theme.colors. Used by the line-prefix path (REPL session preprocessors); line prefixes carry no per-capture styling.
Highlights.format_styled — Method
format_styled(io::IO, ::MIME"text/html", text::AbstractString, color::Int, theme::Theme;
stylesheet=false, classprefix="hl")Output text with a single color for HTML. Color 0 uses theme foreground, 1-16 use theme.colors. Used by the line-prefix path (REPL session preprocessors); line prefixes carry no per-capture styling.
Highlights.format_styled — Method
format_styled(io::IO, ::MIME"text/latex", text::AbstractString, color::Int, theme::Theme;
stylesheet=false, classprefix="hl")Output text with a single color for LaTeX. Color 0 uses theme foreground, 1-16 use theme.colors. Used by the line-prefix path (REPL session preprocessors); line prefixes carry no per-capture styling.
Highlights.format_styled — Method
format_styled(io::IO, ::MIME"text/plain", text::AbstractString, color::Int, theme::Theme)Output text without styling for plain format.
Highlights.format_styled — Method
format_styled(io::IO, ::MIME"text/typst", text::AbstractString, color::Int, theme::Theme)Output text with a single color for Typst. Color 0 uses theme foreground, 1-16 use theme.colors. Used by the line-prefix path (REPL session preprocessors); line prefixes carry no per-capture styling.
Highlights.get_capture_color — Method
get_capture_color(capture_name::AbstractString, mapping::Dict) -> IntGet color index for a capture name, with hierarchical fallback.
Highlights.get_capture_priority — Method
get_capture_priority(capture_name::AbstractString, priorities::Dict) -> IntGet priority for a capture name, with hierarchical fallback.
Highlights.get_capture_styles — Method
get_capture_styles(capture_name::AbstractString, theme) -> Vector{Symbol}Get text styles (subset of :bold, :italic, :underline) for a capture name, with hierarchical fallback. Returns an empty vector if no style is set.
Highlights.hex_to_latex_color — Method
hex_to_latex_color(hex::AbstractString) -> StringConvert hex color to LaTeX RGB color specification.
Highlights.hex_to_rgb — Method
hex_to_rgb(hex::AbstractString) -> Tuple{Int,Int,Int}Convert a hex color string (e.g., "#DB2D20" or "DB2D20") to RGB tuple.
Highlights.highlight_tokens — Method
highlight_tokens(parser::TreeSitter.Parser, query::TreeSitter.Query, source::AbstractString;
priorities::Dict=default_capture_priorities()) -> Vector{HighlightToken}Extract highlight tokens from source code, sorted by position.
Highlights.is_content_capture — Method
is_content_capture(name::AbstractString) -> BoolWhether a capture name denotes literal text content (string, comment, character) whose whitespace must be preserved rather than trimmed.
Highlights.jlcon_preprocess — Method
jlcon_preprocess(source::AbstractString) -> Vector{Segment}Preprocess Julia REPL (jlcon) sessions into segments.
Recognizes four prompt modes:
julia>- Normal mode (green, highlighted as Julia)help?>- Help mode (yellow, highlighted as Julia)shell>- Shell mode (red, highlighted as Bash)pkg>- Package mode (blue, plain text)
Highlights.levenshtein — Method
levenshtein(a::AbstractString, b::AbstractString) -> IntCompute Levenshtein (edit) distance between two strings.
Highlights.load_theme — Method
load_theme(name::String) -> ThemeLoad a theme by name or file path. Built-in themes are cached; file-based themes are not.
Highlights.normalize_language — Method
normalize_language(lang) -> SymbolNormalize a language to a canonical Symbol (lowercase, alias-resolved).
Highlights.parse_theme — Method
parse_theme(data) -> ThemeParse raw theme dictionary into a Theme struct.
Highlights.preprocessor — Method
preprocessor(::MIME) -> Union{Function, Nothing}Return the preprocessor function for a language MIME type, or nothing if none.
Users can extend for custom pseudo-languages:
Highlights.preprocessor(::MIME"text/myrepl") = my_repl_preprocessHighlights.pycon_preprocess — Method
pycon_preprocess(source::AbstractString) -> Vector{Segment}Preprocess Python REPL (pycon) sessions into segments.
>>>- Primary prompt (yellow)...- Continuation prompt (yellow)
Highlights.rcon_preprocess — Method
rcon_preprocess(source::AbstractString) -> Vector{Segment}Preprocess R REPL (rcon) sessions into segments.
>- Primary prompt (blue)+- Continuation prompt (blue)
Highlights.repl_preprocess — Method
repl_preprocess(source::AbstractString, config::ReplConfig) -> Vector{Segment}Generic REPL session preprocessor. Handles prompts, continuations, and output.
Highlights.resolve_language — Method
resolve_language(lang::Module) -> Module
resolve_language(lang::Union{Symbol,AbstractString}) -> ModuleResolve a language specification to a JLL module. Supports case-insensitive names and common aliases.
Highlights.rgb_to_hex — Method
rgb_to_hex(r::Int, g::Int, b::Int) -> StringConvert RGB values to a hex color string (e.g., "#DB2D20").
Highlights.suggest_language_jlls — Method
suggest_language_jlls(query::String, jlls::Vector{String}; limit::Int=5) -> Vector{Tuple{String,String}}Return (languagename, jllpackage) pairs sorted by similarity to query. Reduces limit when top match is much better than alternatives.
Highlights.suggest_themes — Method
suggest_themes(query::String, themes::Vector{String}; limit::Int=5) -> Vector{String}Find themes most similar to query based on edit distance (case-insensitive).
Highlights.trim_capture — Method
trim_capture(text::AbstractString, byte_range::Tuple{Int,Int}) -> Union{Tuple{String,Tuple{Int,Int}},Nothing}Trim leading and trailing whitespace from a capture span so styling does not bleed onto the spaces and newlines between tokens. Returns the trimmed text and adjusted byte range, or nothing when the span is entirely whitespace.
Highlights.write_typst_raw — Method
write_typst_raw(io::IO, s::AbstractString)Write text as Typst raw content #raw("...") which preserves whitespace.
Highlights.write_typst_str — Method
write_typst_str(io::IO, s::AbstractString)Write string as Typst raw string #"..." preserving whitespace.