Skip to content

Core API

Engine

ExpressiveCodeEngine

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.

Constructors

new ExpressiveCodeEngine(config)

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.

Arguments
ParameterType
configExpressiveCodeEngineConfig

Methods

getBaseStyles()
  • 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()
  • 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()
  • 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()
  • 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.

Arguments
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.
Returns

Promise<Object>

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

Properties

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

Code blocks

ExpressiveCodeBlock

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

Usage example

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'

Constructors

new ExpressiveCodeBlock(options)
Arguments
ParameterType
optionsExpressiveCodeBlockOptions

Methods

deleteLine()
  • deleteLine(index): void

Deletes the line at the given index.

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

Arguments
ParameterType
indexnumber
deleteLines()
  • 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.

Arguments
ParameterType
indicesnumber[]
getLine()

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

Arguments
ParameterType
indexnumber
getLines()

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.

Arguments
ParameterType
startIndex?number
endIndex?number
insertLine()

Inserts a new line at the given index.

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

Arguments
ParameterType
indexnumber
textLinestring
insertLines()

Inserts multiple new lines at the given index.

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

Arguments
ParameterType
indexnumber
textLinesstring[]

Accessors

code
  • get code(): string

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

language
  • 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.

Parameters
ParameterType
valuestring
locale
  • 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.

meta
  • 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.

Parameters
ParameterType
valuestring
metaOptions

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

parentDocument
  • 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.

props

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.

state

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.

ExpressiveCodeBlockOptions

Properties

code
Type: string

The plaintext contents of the code block.

language
Type: string

The code block’s language.

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

locale?
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.

meta?
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.

parentDocument?
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.

Object properties
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.

props?
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.

ExpressiveCodeLine

Constructors

new ExpressiveCodeLine(text)
Arguments
ParameterType
textstring

Methods

addAnnotation()
  • addAnnotation(annotation): void
Arguments
ParameterType
annotationExpressiveCodeAnnotation
deleteAnnotation()
  • deleteAnnotation(annotation): void
Arguments
ParameterType
annotationExpressiveCodeAnnotation
editText()
  • editText(columnStart, columnEnd, newText): string
Arguments
ParameterType
columnStartundefined | number
columnEndundefined | number
newTextstring
getAnnotations()

Accessors

parent
Parameters
ParameterType
valueundefined | ExpressiveCodeBlock
text
  • get text(): string

MetaOptions

Constructors

new MetaOptions(input)
Arguments
ParameterType
inputstring

Methods

getBoolean()
  • getBoolean(key): undefined | boolean

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

Arguments
ParameterType
keystring
getInteger()
  • getInteger(key): undefined | number

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

Arguments
ParameterType
keystring
getIntegers()
  • 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.

Arguments
ParameterType
keyOrKeys?string | string[]
getRange()
  • 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.

Arguments
ParameterType
keystring
getRanges()
  • 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.

Arguments
ParameterType
keyOrKeys?string | string[]
getRegExp()
  • 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.

Arguments
ParameterType
keystring
getRegExps()
  • 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.

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

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

Arguments
ParameterType
keystring
getStrings()
  • 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.

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

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

Type parameters
ParameterValue
K extends undefined | "string" | "boolean" | "range" | "regexp"undefined
Arguments
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()
  • value<K>(key, kind?): undefined | OptionType[“value”]
Type parameters
ParameterValue
K extends undefined | "string" | "boolean" | "range" | "regexp"undefined
Arguments
ParameterType
keystring
kind?K

Accessors

errors
  • get errors(): undefined | string[]

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

Themes

ExpressiveCodeTheme

Constructors

new ExpressiveCodeTheme(theme)

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.

Arguments
ParameterType
themeExpressiveCodeThemeInput

Methods

applyHueAndChromaAdjustments()

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.

Arguments
ParameterType
adjustmentsObject
adjustments.accents?string | ChromaticRecolorTarget
adjustments.backgrounds?string | ChromaticRecolorTarget
adjustments.custom?Object[]
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.

Arguments
ParameterTypeDefault value
minContrastnumber5.5
backgroundColor?stringundefined
fromJSONString()

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.

Arguments
ParameterType
jsonstring

Properties

bg
Type: string
colors
Type: Object (mapping VS Code workbench color keys to values)
fg
Type: string
name
Type: string
semanticHighlighting
Type: boolean
settings
Type: ThemeSetting[]
styleOverrides

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
Type: "dark" | "light"

Annotations

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.

ExpressiveCodeAnnotation

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.

Constructors

Methods

abstract render()
  • 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.

Arguments
ParameterType
optionsAnnotationRenderOptions

Properties

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

InlineStyleAnnotation

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.

Usage example

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!')

Constructors

new InlineStyleAnnotation(options)
Arguments
ParameterType
optionsInlineStyleAnnotationOptions

Methods

render()
  • 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.

Arguments
ParameterType
optionsAnnotationRenderOptions

Properties

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.

Referenced types

AnnotationBaseOptions

Type: Object

Object properties

inlineRange
renderPhase

AnnotationRenderOptions

Type: ResolverContext & Object

Object properties

line
lineIndex
Type: number
nodesToTransform
Type: Parents[]

AnnotationRenderPhase

Type: "earliest" | "earlier" | "normal" | "later" | "latest"

ChromaticRecolorTarget

Type: Object

Object properties

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.

ExpressiveCodeInlineRange

Type: Object

Object properties

columnEnd
Type: number
columnStart
Type: number

ExpressiveCodeProcessingState

Properties

canEditAnnotations
Type: boolean
canEditCode
Type: boolean
canEditLanguage
Type: boolean
canEditMetadata
Type: boolean

InlineStyleAnnotationOptions

Type: AnnotationBaseOptions & Object

Object properties

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.

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.

RenderInput

RenderOptions

Properties

onInitGroup?
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... }).

Arguments
ParameterType
groupContentsreadonly { codeBlock: ExpressiveCodeBlock }[]

ThemeSetting

Type: Object

Object properties

settings
Type: Object
settings.fontStyle
Type: string
settings.foreground
Type: string
name
Type: string
scope
Type: string[]