API Reference

Public API

Highlights.HighlightType
Highlight

Displayable 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 output

Constructors

Highlight(source, language, theme; kwargs...)

Arguments and keyword arguments match highlight.

source
Highlights.ThemeType
Theme

Represents a color theme with 16 ANSI colors and special colors.

Fields

  • name::String: Theme name
  • colors::Dict{Int,String}: Maps color index (1-16) to hex color string
  • background::String: Background color (hex)
  • foreground::String: Default text color (hex)

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")

# 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"))
source
Highlights.highlightMethod
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 highlight
  • language: Language specifier - JLL module, Symbol, or String (e.g., :julia, "python")
  • theme: Theme name (String) or Theme object (see available_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 color
    • MIME("text/html") or "text/html" - HTML with inline styles
    • MIME("text/latex") or "text/latex" - LaTeX with color commands
    • MIME("text/plain") or "text/plain" - Debug format with capture names
  • transform: Function to wrap tokens (see default_transform)

Language Resolution

Languages are case-insensitive and support common aliases:

  • jsjavascript
  • tstypescript
  • pypython
  • rbruby
  • ymlyaml
  • rsrust
  • csc_sharp
  • c++, cxxcpp
  • sh, shell, zshbash
  • jljulia

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))
source
Highlights.stylesheetMethod
stylesheet(theme_name::String; classprefix="hl") -> String
stylesheet(mime, theme_name::String; classprefix="hl") -> String
stylesheet(io::IO, mime, theme_name::String; classprefix="hl")

Generate a stylesheet for class-based syntax highlighting.

Arguments

  • classprefix: Prefix for CSS classes/LaTeX commands (default "hl")

Supported MIME types

  • MIME"text/css" - Raw CSS rules
  • MIME"text/html" - CSS wrapped in <style> tags
  • MIME"text/latex" - LaTeX \newcommand definitions

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
source

Internal API

Highlights.CodeSegmentType
CodeSegment

A code block to be syntax-highlighted with TreeSitter.

Fields

  • text::String: Source code
  • language::Symbol: Language to highlight as (e.g., :julia, :bash)
  • line_prefixes::Vector{Tuple{String,Int}}: (prefix, color) for each line (e.g., continuation prompts)
source
Highlights.HighlightTokenType
HighlightToken

Represents a syntax-highlighted token with position and AST information.

Fields

  • text: The token text
  • capture: Tree-sitter capture name (e.g., "function.call")
  • byte_range: Start and end byte positions in source
  • node: Original TreeSitter.Node for AST navigation (Nothing for synthetic tokens)
source
Highlights.ReplConfigType
ReplConfig

Configuration 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
source
Highlights.ReplModeType
ReplMode

Configuration 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 display
  • color::Int: Color index for the prompt
  • language::Union{Symbol,Nothing}: Language for syntax highlighting, or nothing for plain text
source
Highlights.StyledSegmentType
StyledSegment

A text block with a single color (no syntax highlighting).

Fields

  • text::String: Text content
  • color::Int: Theme color index (1-16), or 0 for foreground
source
Highlights.ansi_color_from_hexMethod
ansi_color_from_hex(hex::AbstractString; background::Bool=false) -> String

Generate ANSI 24-bit true color escape sequence from hex color string.

source
Highlights.ansi_color_rgbMethod
ansi_color_rgb(r::Int, g::Int, b::Int; background::Bool=false) -> String

Generate ANSI 24-bit true color escape sequence.

source
Highlights.available_languagesMethod
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

source
Highlights.color_distanceMethod
color_distance(c1::AbstractString, c2::AbstractString) -> Float64

Compute perceptual distance between two hex colors.

source
Highlights.deduplicate_tokensMethod
deduplicate_tokens(tokens::Vector{HighlightToken}, priorities::Dict) -> Vector{HighlightToken}

Layer overlapping tokens, preferring more specific (shorter) tokens. For identical ranges, highest priority wins.

source
Highlights.default_transformMethod
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=true before the token is rendered (write opening wrapper)
  • entering=false after the token is rendered (write closing wrapper)

Arguments

  • io: Output stream to write wrapper content
  • mime: Output format MIME type
  • token: The token with .text, .capture, .byte_range, .node
  • entering: true before rendering, false after
  • source: 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)
source
Highlights.escape_htmlMethod
escape_html(io::IO, s::AbstractString)
escape_html(s::AbstractString) -> String

Escape HTML special characters.

source
Highlights.escape_latexMethod
escape_latex(io::IO, s::AbstractString)
escape_latex(s::AbstractString) -> String

Escape LaTeX special characters.

source
Highlights.formatMethod
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).

source
Highlights.formatMethod
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).

source
Highlights.formatMethod
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).

source
Highlights.formatMethod
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.

source
Highlights.formatMethod
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).

source
Highlights.format_styledMethod
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.

source
Highlights.format_styledMethod
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.

source
Highlights.format_styledMethod
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.

source
Highlights.format_styledMethod
format_styled(io::IO, ::MIME"text/plain", text::AbstractString, color::Int, theme::Theme)

Output text without styling for plain format.

source
Highlights.format_styledMethod
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.

source
Highlights.get_capture_colorMethod
get_capture_color(capture_name::AbstractString, mapping::Dict) -> Int

Get color index for a capture name, with hierarchical fallback.

source
Highlights.hex_to_rgbMethod
hex_to_rgb(hex::AbstractString) -> Tuple{Int,Int,Int}

Convert a hex color string (e.g., "#DB2D20" or "DB2D20") to RGB tuple.

source
Highlights.highlight_tokensMethod
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.

source
Highlights.jlcon_preprocessMethod
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)
source
Highlights.levenshteinMethod
levenshtein(a::AbstractString, b::AbstractString) -> Int

Compute Levenshtein (edit) distance between two strings.

source
Highlights.load_themeMethod
load_theme(name::String) -> Theme

Load a theme by name or file path. Built-in themes are cached; file-based themes are not.

source
Highlights.preprocessorMethod
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_preprocess
source
Highlights.pycon_preprocessMethod
pycon_preprocess(source::AbstractString) -> Vector{Segment}

Preprocess Python REPL (pycon) sessions into segments.

  • >>> - Primary prompt (yellow)
  • ... - Continuation prompt (yellow)
source
Highlights.rcon_preprocessMethod
rcon_preprocess(source::AbstractString) -> Vector{Segment}

Preprocess R REPL (rcon) sessions into segments.

  • > - Primary prompt (blue)
  • + - Continuation prompt (blue)
source
Highlights.repl_preprocessMethod
repl_preprocess(source::AbstractString, config::ReplConfig) -> Vector{Segment}

Generic REPL session preprocessor. Handles prompts, continuations, and output.

source
Highlights.resolve_languageMethod
resolve_language(lang::Module) -> Module
resolve_language(lang::Union{Symbol,AbstractString}) -> Module

Resolve a language specification to a JLL module. Supports case-insensitive names and common aliases.

source
Highlights.rgb_to_hexMethod
rgb_to_hex(r::Int, g::Int, b::Int) -> String

Convert RGB values to a hex color string (e.g., "#DB2D20").

source
Highlights.suggest_language_jllsMethod
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.

source
Highlights.suggest_themesMethod
suggest_themes(query::String, themes::Vector{String}; limit::Int=5) -> Vector{String}

Find themes most similar to query based on edit distance (case-insensitive).

source