Skip to content

Core API

The Expressive Code engine is responsible for rendering code blocks to a Hypertext Abstract Syntax Tree (HAST) that can be serialized to HTML, as well as generating the required CSS styles and JS modules.

It also provides read-only access to all resolved configuration options through its public properties.

Creates a new instance of the Expressive Code engine.

To minimize overhead caused by loading plugins, you can create a single instance for your application and keep using it to render all your code blocks.

ParameterType
configExpressiveCodeEngineConfig
  • getBaseStyles(): Promise<string>

Returns a string containing all CSS styles that should be added to every page using Expressive Code. These styles are static base styles which do not depend on the configured theme(s).

The calling code must take care of actually adding the returned styles to the page.

Please note that the styles contain references to CSS variables, which must also be added to the page. These can be obtained by calling getThemeStyles.

  • getJsModules(): Promise<string[]>

Returns an array of JavaScript modules (pure code without any wrapping script tags) that should be added to every page containing code blocks.

The contents are collected from the jsModules property of all registered plugins. Any duplicates are removed.

The calling code must take care of actually adding the collected scripts to the page. For example, it could create site-wide JavaScript files from the returned modules and refer to them in a script tag with type="module", or it could insert them into inline <script type="module"> elements.

  • getThemeStyles(): Promise<string>

Returns a string containing theme-dependent styles that should be added to every page using Expressive Code. These styles contain CSS variable declarations that are generated automatically based on the configured themes, useDarkModeMediaQuery and themeCssSelector config options.

The first theme defined in the themes option is considered the “base theme”, for which a full set of CSS variables is declared and scoped to the selector defined by the themeCssRoot option (defaults to :root).

For all alternate themes, a differential set of CSS variables is declared for cases where their values differ from the base theme, and scoped to theme-specific selectors that are generated by combining themeCssRoot with the theme selector specified by this option.

The calling code must take care of actually adding the returned styles to the page.

Please note that these styles must be added to the page together with the base styles returned by getBaseStyles.

  • render(input, options?): Promise<Object>

Renders the given code block(s) and returns the rendered group & block ASTs, the rendered code block contents after all transformations have been applied, and a set of non-global CSS styles required by the rendered code blocks.

In Expressive Code, all processing of your code blocks and their metadata is performed by plugins. To render markup around lines or inline ranges of characters, the render method calls the hook functions registered by all added plugins.

ParameterTypeDescription
inputRenderInputThe code block(s) to render. Can either be an ExpressiveCodeBlockOptions object containing the properties required to create a new ExpressiveCodeBlock internally, an existing ExpressiveCodeBlock, or an array containing any combination of these.
options?RenderOptionsOptional configuration options for the rendering process.

Promise<Object>

renderedGroupAst
Type: Element
renderedGroupContents
Type: RenderedGroupContents
styles
Type: Set<string>

All config options that can be passed to the constructor are also available on the instance as read-only properties.

Represents a single code block that can be rendered by the Expressive Code engine.

codeBlockExample.js
import { ExpressiveCodeBlock } from 'expressive-code'
const codePlaintext = `
// Perform very important calculations
const a = 1 + 2
`
const codeBlock = new ExpressiveCodeBlock({
code: codePlaintext.trim(),
language: 'js',
})
// Delete the first line and output the remaining code
codeBlock.deleteLine(0)
console.dir(codeBlock.code)
// --> 'const a = 1 + 2'
ParameterType
optionsExpressiveCodeBlockOptions
  • deleteLine(index): void

Deletes the line at the given index.

May throw an error if not allowed in the current state.

ParameterType
indexnumber
  • deleteLines(indices): void

Deletes the lines at the given indices.

This function automatically sorts the indices in descending order before deleting the lines, so you do not need to worry about indices shifting after deleting a line.

May throw an error if not allowed in the current state.

ParameterType
indicesnumber[]

Returns the line at the given index, or undefined if the index is out of range.

ParameterType
indexnumber

Returns a readonly array of lines starting at the given index and ending before the given index (exclusive). The indices support the same syntax as JavaScript’s Array.slice method.

ParameterType
startIndex?number
endIndex?number

Inserts a new line at the given index.

May throw an error if not allowed in the current state.

ParameterType
indexnumber
textLinestring

Inserts multiple new lines at the given index.

May throw an error if not allowed in the current state.

ParameterType
indexnumber
textLinesstring[]
  • get code(): string

Provides read-only access to the code block’s plaintext contents.

  • get language(): string
  • set language(value): void

Allows getting and setting the code block’s language.

Setting this property may throw an error if not allowed in the current state.

ParameterType
valuestring
  • get locale(): undefined | string

Allows getting the code block’s locale (e.g. en-US or de-DE). It is used by plugins to display localized strings depending on the language of the containing page.

Integrations like rehype-expressive-code support multi-language sites by allowing you to provide custom logic to determine a block’s locale (e.g. based on its parent document).

If no locale is defined here, ExpressiveCodeEngine will render the code block using the defaultLocale provided in its configuration.

  • get meta(): string
  • set meta(value): void

Allows getting or setting the code block’s meta string. In markdown or MDX documents, this is the part of the code block’s opening fence that comes after the language name.

Setting this property may throw an error if not allowed in the current state.

ParameterType
valuestring

Provides read-only access to the parsed version of the block’s meta string.

  • get parentDocument(): undefined | Object

Provides read-only access to optional data about the parent document the code block is located in.

Integrations like rehype-expressive-code can provide this information based on the source document being processed. There may be cases where no document is available, e.g. when the code block was created dynamically.

Provides access to the code block’s props.

To allow users to set these props through the meta string, plugins can use the preprocessMetadata hook to read metaOptions and update their props accordingly.

Props can be modified until rendering starts and become read-only afterwards.

Provides read-only access to the code block’s processing state.

The processing state controls which properties of the code block can be modified. The engine updates it automatically during rendering.

Type: string

The plaintext contents of the code block.

Type: string

The code block’s language.

Please use a valid language identifier to ensure proper syntax highlighting.

Type: string

The code block’s locale (e.g. en-US or de-DE). This is used by plugins to display localized strings depending on the language of the containing page.

If no locale is defined here, most Expressive Code integrations will attempt to auto-detect the block locale using the configured getBlockLocale function, and finally fall back to the configured defaultLocale.

Type: string

An optional meta string. In markdown or MDX documents, this is the part of the code block’s opening fence that comes after the language name.

Type: Object

Optional data about the parent document the code block is located in.

Integrations like rehype-expressive-code can provide this information based on the source document being processed. There may be cases where no document is available, e.g. when the code block was created dynamically.

documentRoot
Type: unknown

A reference to the object representing the parsed source document. This reference will stay the same for all code blocks in the same document.

For example, if you are using rehype-expressive-code to render code blocks in a Markdown file, this would be the hast node representing the file’s root node.

positionInDocument
Type: Object

Data about the position of the code block in the parent document.

positionInDocument.groupIndex
Type: number
positionInDocument.totalGroups
Type: number
sourceFilePath
Type: string

The full path to the source file containing the code block.

Type: Partial<ExpressiveCodeBlockProps>

Optional props that can be used to influence the rendering of this code block.

Plugins can add their own props to this type. To allow users to set these props through the meta string, plugins can use the preprocessMetadata hook to read metaOptions and update the props object accordingly.

ParameterType
textstring
  • addAnnotation(annotation): void
ParameterType
annotationExpressiveCodeAnnotation
  • deleteAnnotation(annotation): void
ParameterType
annotationExpressiveCodeAnnotation
  • editText(columnStart, columnEnd, newText): string
ParameterType
columnStartundefined | number
columnEndundefined | number
newTextstring
ParameterType
valueundefined | ExpressiveCodeBlock
  • get text(): string
ParameterType
inputstring
  • getBoolean(key): undefined | boolean

Returns the last boolean value with the given key (case-insensitive).

ParameterType
keystring
  • getInteger(key): undefined | number

Returns the last integer value with the given key (case-insensitive), or without a key by passing an empty string.

ParameterType
keystring
  • getIntegers(keyOrKeys?): number[]

Returns an array of all integer values with the given keys (case-insensitive), or without a key by passing an empty string.

ParameterType
keyOrKeys?string | string[]
  • getRange(key): undefined | string

Returns the last range value ({value}) with the given key (case-insensitive), or without a key by passing an empty string.

ParameterType
keystring
  • getRanges(keyOrKeys?): string[]

Returns an array of all range values ({value}) with the given keys (case-insensitive), or without a key by passing an empty string.

ParameterType
keyOrKeys?string | string[]
  • getRegExp(key): undefined | RegExp

Returns the last RegExp value (/value/) with the given key (case-insensitive), or without a key by passing an empty string.

ParameterType
keystring
  • getRegExps(keyOrKeys?): RegExp[]

Returns an array of all RegExp values (/value/) with the given keys (case-insensitive), or without a key by passing an empty string.

ParameterType
keyOrKeys?string | string[]
  • getString(key): undefined | string

Returns the last string value with the given key (case-insensitive), or without a key by passing an empty string.

ParameterType
keystring
  • getStrings(keyOrKeys?): string[]

Returns an array of all string values with the given keys (case-insensitive), or without a key by passing an empty string.

ParameterType
keyOrKeys?string | string[]
  • list<K>(keyOrKeys?, kind?): ReturnType

Returns a list of meta options, optionally filtered by their key and/or MetaOptionKind.

ParameterValue
K extends undefined | "string" | "boolean" | "range" | "regexp"undefined
ParameterTypeDescription
keyOrKeys?string | string[]Allows to filter the options by key. An empty string will return options without a key. A non-empty string will return options with a matching key (case-insensitive). An array of strings will return options with any of the matching keys. If omitted, no key-based filtering will be applied.
kind?KAllows to filter the options by MetaOptionKind. If omitted, no kind-based filtering will be applied.
  • value<K>(key, kind?): undefined | OptionType[“value”]
ParameterValue
K extends undefined | "string" | "boolean" | "range" | "regexp"undefined
ParameterType
keystring
kind?K
  • get errors(): undefined | string[]

A list of error messages that occurred when parsing the meta string, or undefined if no errors occurred.

Loads the given theme for use with Expressive Code. Supports both Shiki and VS Code themes.

You can also pass an existing ExpressiveCodeTheme instance to create a copy of it.

Note: To save on bundle size, this constructor does not support loading themes bundled with Shiki by name (e.g. dracula). Instead, import Shiki’s loadTheme function yourself, use it to load its bundled theme (e.g. themes/dracula.json), and pass the result to this constructor.

ParameterType
themeExpressiveCodeThemeInput

Applies chromatic adjustments to entire groups of theme colors while keeping their relative lightness and alpha components intact. This can be used to quickly create theme variants that fit the color scheme of any website or brand.

Adjustments can either be defined as hue and chroma values in the OKLCH color space (range 0–360 for hue, 0–0.4 for chroma), or these values can be extracted from hex color strings (e.g. #3b82f6).

You can target predefined groups of theme colors (e.g. backgrounds, accents) and/or use the custom property to define your own groups of theme colors to be adjusted. Each custom group must contain a themeColorKeys property with an array of VS Code theme color keys (e.g. ['panel.background', 'panel.border']) and a targetHueAndChroma property that accepts the same adjustment target values as backgrounds and accents. Custom groups will be applied in the order they are defined.

Returns the same ExpressiveCodeTheme instance to allow chaining.

ParameterType
adjustmentsObject
adjustments.accents?string | ChromaticRecolorTarget
adjustments.backgrounds?string | ChromaticRecolorTarget
adjustments.custom?Object[]
ensureMinSyntaxHighlightingColorContrast()
Section titled “ensureMinSyntaxHighlightingColorContrast()”

Processes the theme’s syntax highlighting colors to ensure a minimum contrast ratio between foreground and background colors.

The default value of 5.5 ensures optimal accessibility with a contrast ratio of 5.5:1.

You can optionally pass a custom background color to use for the contrast checks. By default, the theme’s background color will be used.

Returns the same ExpressiveCodeTheme instance to allow chaining.

ParameterTypeDefault value
minContrastnumber5.5
backgroundColor?stringundefined

Attempts to parse the given JSON string as a theme.

As some themes follow the JSONC format and may contain comments and trailing commas, this method will attempt to strip them before parsing the result.

ParameterType
jsonstring
Type: string
Type: Object (mapping VS Code workbench color keys to values)
Type: string
Type: string
Type: boolean
Type: ThemeSetting[]

An optional set of style overrides that can be used to customize the appearance of the rendered code blocks without having to write custom CSS.

See Overriding Styles for a list of all available settings.

Type: "dark" | "light"

In Expressive Code, annotations are used by plugins to attach semantic information to lines or inline ranges of code. They are used to represent things like syntax highlighting, text markers, comments, errors, warnings, and other semantic information.

Annotations must provide a render function that transforms its contained AST nodes, e.g. by wrapping them in HTML tags. This function is called by the engine when it’s time to render the line the annotation has been attached to.

An abstract class representing a single annotation attached to a code line.

You can develop your own annotations by extending this class and providing implementations for its abstract methods. See the implementation of the InlineStyleAnnotation class for an example.

You can also define your annotations as plain objects, as long as they have the same properties as this class. This allows you to use annotations in a more functional way, without the need to extend a class.

  • abstract render(options): Parents[]

Renders the annotation by transforming the provided nodes.

This function will be called with an array of AST nodes to transform, and is expected to return an array containing the same number of nodes.

For example, you could use the hastscript library to wrap the received nodes in HTML elements.

ParameterType
optionsAnnotationRenderOptions

All annotation base options are available on the instance as read-only properties. See AnnotationBaseOptions for the entire list.

A theme-dependent inline style annotation that allows changing colors, font styles and decorations of the targeted code. This annotation is used by the syntax highlighting plugin to apply colors and styles to syntax tokens, and you can use it in your own plugins as well.

You can add as many inline style annotations to a line as you want, even targeting the same code with multiple fully or partially overlapping annotation ranges. During rendering, these annotations will be automatically optimized to avoid creating unnecessary HTML elements.

In the following example, we create a plugin that makes the first word of each code block red in the first theme. We do this by adding an InlineStyleAnnotation to the first line of each code block.

plugins/plugin-first-word-red.js
// @ts-check
import { definePlugin, InlineStyleAnnotation } from '@expressive-code/core'
export function pluginFirstWordRed() {
return definePlugin({
name: 'Make first word red',
hooks: {
postprocessAnalyzedCode: (context) => {
// Only apply this to code blocks with the `first-word-red` meta
if (!context.codeBlock.meta.includes('first-word-red')) return
// Get the first line of the code block
const firstLine = context.codeBlock.getLine(0)
if (!firstLine) return
// Find the end of the first word
const firstWordEnd = firstLine.text.match(/(?<=\w)\W/)?.index ?? -1
if (firstWordEnd <= 0) return
// Add an annotation that makes the first word red
firstLine.addAnnotation(
new InlineStyleAnnotation({
inlineRange: {
columnStart: 0,
columnEnd: firstWordEnd,
},
color: '#ff0000',
// Only apply the red color to the first configured theme
styleVariantIndex: 0,
})
)
},
},
})
}

After adding this plugin to your configuration, you can use it like this:

```js first-word-red
consule.log('Hello world!')
```

The rendered code block will now have a red text color applied to the first word, but only in the dark theme (the first theme in the configuration):

consule.log('Hello world!')
ParameterType
optionsInlineStyleAnnotationOptions
  • render(options): Parents[]

Renders the annotation by transforming the provided nodes.

This function will be called with an array of AST nodes to transform, and is expected to return an array containing the same number of nodes.

For example, you could use the hastscript library to wrap the received nodes in HTML elements.

ParameterType
optionsAnnotationRenderOptions

All config options that can be passed to the constructor are also available on the instance as read-only properties.

See InlineStyleAnnotationOptions for the entire list.

  • createInlineSvgUrl(svgContents, options): string

Creates an inline SVG image data URL from the given contents of an SVG file.

You can use it to embed SVG images directly into a plugin’s styles or HAST, or pass it to an existing styleOverrides icon setting.

The optional options argument allows further customization of the generated URL.

ParameterType
svgContentsstring | string[]
optionsCreateInlineSvgUrlOptions
  • getColorContrast(color1, color2): number
ParameterType
color1string
color2string
  • getColorContrastOnBackground(input, background): number
ParameterType
inputstring
backgroundstring
  • getFirstStaticColor(…inputs): undefined | string

Given any number of input colors, which may include CSS variables with optional fallbacks, returns the first static color.

Returns undefined if no parseable static color can be found.

ParameterType
inputs(undefined | string)[]
  • getLuminance(input): number

Returns the luminance of a color. Luminance values are between 0 and 1.

ParameterType
inputstring
  • getStaticBackgroundColor(styleVariant): string

Determine a static background color based on the given style variant, trying to resolve fallback values of CSS variables if necessary.

This color is intended to be used for contrast calculations, not as an actual background color.

ParameterType
styleVariantStyleVariant
  • changeAlphaToReachColorContrast(input, background, minContrast, maxContrast): string
ParameterTypeDefault value
inputstringundefined
backgroundstringundefined
minContrastnumber6
maxContrastnumber22
  • changeLuminanceToReachColorContrast(input1, input2, minContrast): string
ParameterTypeDefault value
input1stringundefined
input2stringundefined
minContrastnumber6
  • darken(input, amount): string

Darkens a color by the given amount. Automatically limits the resulting lightness value to the range 0 to 1.

ParameterType
inputstring
amountnumber
  • ensureColorContrastOnBackground(input, background, minContrast, maxContrast): string

Modifies the luminance and/or the alpha value of a color to ensure its color contrast on the given background color is within the given range.

  • If the contrast is too low, the luminance is either increased or decreased first, and then the alpha value is increased (if required).
  • If the contrast is too high, only the alpha value is decreased.

If the target contrast cannot be reached, the function will try to get as close as possible.

ParameterTypeDefault value
inputstringundefined
backgroundstringundefined
minContrastnumber5.5
maxContrastnumber22
  • lighten(input, amount): string

Lightens a color by the given amount. Automatically limits the resulting lightness value to the range 0 to 1.

ParameterType
inputstring
amountnumber
  • mix(input, mixinInput, amount): string

Mixes the second color into the first color by the given amount. Amount should be between 0 and 1.

ParameterType
inputstring
mixinInputstring
amountnumber
  • multiplyAlpha(input, factor): string

Multiplies the existing alpha value of a color with the given factor. Automatically limits the resulting alpha value to the range 0 to 1.

ParameterType
inputstring
factornumber
  • onBackground(input, background): string

Computes how the first color would look on top of the second color.

ParameterType
inputstring
backgroundstring
  • setAlpha(input, newAlpha): string

Overrides the alpha value of a color with the given value. Values should be between 0 and 1.

ParameterType
inputstring
newAlphanumber
  • setLuminance(input, targetLuminance): string

Mixes a color with white or black to achieve the desired luminance. Luminance values should be between 0 and 1.

ParameterType
inputstring
targetLuminancenumber
Type: Object
inlineRange
renderPhase
Type: ResolverContext & Object
line
lineIndex
Type: number
nodesToTransform
Type: Parents[]
Type: "earliest" | "earlier" | "normal" | "later" | "latest"
Type: Object
chroma
Type: number

The target chroma (0 – 0.4).

If the input color’s lightness is very high, the resulting chroma may be lower than this value. This avoids results that appear too saturated in comparison to the input color.

hue
Type: number

The target hue in degrees (0 – 360).

chromaMeasuredAtLightness
Type: number

The lightness (0 – 1) that the target chroma was measured at.

If given, the chroma will be adjusted relative to this lightness before applying it to the input color.

Type: Object
keepSize
Type: boolean

Whether to keep the original size of the SVG image.

By default, any width and height attributes inside the SVG tag are removed.

Type: Object
columnEnd
Type: number
columnStart
Type: number
Type: boolean
Type: boolean
Type: boolean
Type: boolean
Type: AnnotationBaseOptions & Object
bgColor
Type: string

The background color of the annotation. This is expected to be a hex color string, e.g. #888. Using CSS variables or other color formats is possible, but prevents automatic color contrast checks from working.

bold
Type: boolean

Whether the annotation should be rendered in bold.

color
Type: string

The color of the annotation. This is expected to be a hex color string, e.g. #888. Using CSS variables or other color formats is possible, but prevents automatic color contrast checks from working.

italic
Type: boolean

Whether the annotation should be rendered in italics.

strikethrough
Type: boolean

Whether the annotation should be rendered with a strikethrough.

styleVariantIndex
Type: number

Inline styles can be theme-dependent, which allows plugins like syntax highlighters to style the same code differently depending on the theme.

To support this, the engine creates a style variant for each theme given in the configuration, and plugins can go through the engine’s styleVariants array to access all the themes.

When adding an inline style annotation to a range of code, you can optionally set this property to a styleVariants array index to indicate that this annotation only applies to a specific theme. If this property is not set, the annotation will apply to all themes.

underline
Type: boolean

Whether the annotation should be rendered with an underline.

Type: (groupContents) => void

An optional handler function that can initialize plugin data for the code block group before processing starts.

Plugins can provide access to their data by exporting a const set to a new AttachedPluginData(...) instance (e.g. myPluginData).

You can then import the const and set onInitGroup to a function that calls myPluginData.setFor(group, { ...data... }).

ParameterType
groupContentsreadonly { codeBlock: ExpressiveCodeBlock }[]
Type: Object
settings
Type: Object
settings.fontStyle
Type: string
settings.foreground
Type: string
name
Type: string
scope
Type: string[]