Collapsible Sections
This optional plugin allows you to reduce long code examples to their relevant parts by collapsing any line ranges that are not relevant to the example.
The lines of collapsed sections will be replaced by a clickable X collapsed lines element. When clicked, the collapsed section will be expanded, showing the previously hidden lines.
Installation
Section titled “Installation”Before being able to use collapsible sections in your code blocks, you need to install the plugin as a dependency and add it to your configuration:
-
Add the package to your site’s dependencies:
Terminal window npm i @expressive-code/plugin-collapsible-sectionsTerminal window pnpm add @expressive-code/plugin-collapsible-sectionsTerminal window yarn add @expressive-code/plugin-collapsible-sections -
Add the plugin to your site’s configuration by passing it in the
pluginslist.In Astro and Starlight projects, we recommend putting this option in
ec.config.mjsto ensure that the<Code>component can still be used on your site.ec.config.mjs import { defineEcConfig } from 'astro-expressive-code'import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections'export default defineEcConfig({plugins: [pluginCollapsibleSections()],})ec.config.mjs import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections'/** @type {import('@astrojs/starlight/expressive-code').StarlightExpressiveCodeOptions} */export default {plugins: [pluginCollapsibleSections()],}next.config.mjs import createMDX from '@next/mdx'import rehypeExpressiveCode from 'rehype-expressive-code'import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections'/** @type {import('rehype-expressive-code').RehypeExpressiveCodeOptions} */const rehypeExpressiveCodeOptions = {plugins: [pluginCollapsibleSections()],}/** @type {import('next').NextConfig} */const nextConfig = {reactStrictMode: true,pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],}const withMDX = createMDX({extension: /\.mdx?$/,options: {remarkPlugins: [],rehypePlugins: [// The nested array structure is required to pass options// to a rehype plugin[rehypeExpressiveCode, rehypeExpressiveCodeOptions],],},})export default withMDX(nextConfig)
Usage in markdown / MDX
Section titled “Usage in markdown / MDX”To mark a section as collapsible, you need to add meta information to your code blocks. This is done by appending collapse={X-Y} to your opening code fence, indicating a collapsed section from line X to (and including) line Y.
You can also collapse multiple sections in a single code block by separating them with commas:
```js collapse={1-5, 12-14, 21-24}// All this boilerplate setup code will be collapsedimport { someBoilerplateEngine } from '@example/some-boilerplate'import { evenMoreBoilerplate } from '@example/even-more-boilerplate'
const engine = someBoilerplateEngine(evenMoreBoilerplate())
// This part of the code will be visible by defaultengine.doSomething(1, 2, 3, calcFn)
function calcFn() { // You can have multiple collapsed sections const a = 1 const b = 2 const c = a + b
// This will remain visible console.log(`Calculation result: ${a} + ${b} = ${c}`) return c}
// All this code until the end of the block will be collapsed againengine.closeConnection()engine.freeMemory()engine.shutdown({ reason: 'End of example boilerplate code' })```Available styles
Section titled “Available styles”The plugin supports different section styles, which can be set per block using the collapseStyle prop:
```js collapse={1-5, 12-14, 21-24} collapseStyle=<your style here>// ...```You can also change the prop’s default value globally to avoid having to specify it for each code block. To do so, add it to the defaultProps configuration option:
import { defineEcConfig } from 'astro-expressive-code'import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections'
export default defineEcConfig({ plugins: [pluginCollapsibleSections()], defaultProps: { // Change the default style of collapsible sections collapseStyle: 'collapsible-auto', },})import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections'
/** @type {import('@astrojs/starlight/expressive-code').StarlightExpressiveCodeOptions} */export default { plugins: [pluginCollapsibleSections()], defaultProps: { // Change the default style of collapsible sections collapseStyle: 'collapsible-auto', },}import createMDX from '@next/mdx'import rehypeExpressiveCode from 'rehype-expressive-code'import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections'
/** @type {import('rehype-expressive-code').RehypeExpressiveCodeOptions} */const rehypeExpressiveCodeOptions = { plugins: [pluginCollapsibleSections()], defaultProps: { // Change the default style of collapsible sections collapseStyle: 'collapsible-auto', },}
/** @type {import('next').NextConfig} */const nextConfig = { reactStrictMode: true, pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],}
const withMDX = createMDX({ extension: /\.mdx?$/, options: { remarkPlugins: [], rehypePlugins: [ // The nested array structure is required to pass options // to a rehype plugin [rehypeExpressiveCode, rehypeExpressiveCodeOptions], ], },})
export default withMDX(nextConfig)In the following sections, you can see the different styles in action.
github (default style)
Section titled “github (default style)”This style is similar to the one used by GitHub. A summary line with an expand icon and the default text X collapsed lines is shown. When expanded, the summary line is replaced by the section’s code lines. It is not possible to re-collapse the section.
5 collapsed lines
// All this boilerplate setup code will be collapsedimport { someBoilerplateEngine } from '@example/some-boilerplate'import { evenMoreBoilerplate } from '@example/even-more-boilerplate'
const engine = someBoilerplateEngine(evenMoreBoilerplate())
// This part of the code will be visible by defaultengine.doSomething(1, 2, 3, calcFn)
function calcFn() { // You can have multiple collapsed sections3 collapsed lines
const a = 1 const b = 2 const c = a + b
// This will remain visible console.log(`Calculation result: ${a} + ${b} = ${c}`) return c}
4 collapsed lines
// All this code until the end of the block will be collapsed againengine.closeConnection()engine.freeMemory()engine.shutdown({ reason: 'End of example boilerplate code' })collapsible-start
Section titled “collapsible-start”When collapsed, the summary line looks like the github style. However, when expanded, it remains visible before the expanded code lines, making it possible to re-collapse the section.
5 collapsed lines
// All this boilerplate setup code will be collapsedimport { someBoilerplateEngine } from '@example/some-boilerplate'import { evenMoreBoilerplate } from '@example/even-more-boilerplate'
const engine = someBoilerplateEngine(evenMoreBoilerplate())
// This part of the code will be visible by defaultengine.doSomething(1, 2, 3, calcFn)
function calcFn() { // You can have multiple collapsed sections3 collapsed lines
const a = 1 const b = 2 const c = a + b
// This will remain visible console.log(`Calculation result: ${a} + ${b} = ${c}`) return c}
4 collapsed lines
// All this code until the end of the block will be collapsed againengine.closeConnection()engine.freeMemory()engine.shutdown({ reason: 'End of example boilerplate code' })collapsible-end
Section titled “collapsible-end”Same as collapsible-start, but the summary line remains visible after the expanded code lines.
5 collapsed lines
// All this boilerplate setup code will be collapsedimport { someBoilerplateEngine } from '@example/some-boilerplate'import { evenMoreBoilerplate } from '@example/even-more-boilerplate'
const engine = someBoilerplateEngine(evenMoreBoilerplate())
// This part of the code will be visible by defaultengine.doSomething(1, 2, 3, calcFn)
function calcFn() { // You can have multiple collapsed sections3 collapsed lines
const a = 1 const b = 2 const c = a + b
// This will remain visible console.log(`Calculation result: ${a} + ${b} = ${c}`) return c}
4 collapsed lines
// All this code until the end of the block will be collapsed againengine.closeConnection()engine.freeMemory()engine.shutdown({ reason: 'End of example boilerplate code' })collapsible-auto
Section titled “collapsible-auto”Automatically selects collapsible-start or collapsible-end based on the location of the collapsible section in the code block. Uses collapsible-start unless the section ends at the end of the code block, in which case collapsible-end is used.
5 collapsed lines
// All this boilerplate setup code will be collapsedimport { someBoilerplateEngine } from '@example/some-boilerplate'import { evenMoreBoilerplate } from '@example/even-more-boilerplate'
const engine = someBoilerplateEngine(evenMoreBoilerplate())
// This part of the code will be visible by defaultengine.doSomething(1, 2, 3, calcFn)
function calcFn() { // You can have multiple collapsed sections3 collapsed lines
const a = 1 const b = 2 const c = a + b
// This will remain visible console.log(`Calculation result: ${a} + ${b} = ${c}`) return c}
4 collapsed lines
// All this code until the end of the block will be collapsed againengine.closeConnection()engine.freeMemory()engine.shutdown({ reason: 'End of example boilerplate code' })Usage in the <Code> component
Section titled “Usage in the <Code> component”The collapsible sections plugin adds the following props to the <Code> component that allow direct access to its features:
collapse
Section titled “collapse”string | string[] Collapses the given line range or ranges.
collapsePreserveIndent
Section titled “collapsePreserveIndent”boolean Default:
true Determines if the summary line content of collapsible sections should be indented to match the minimum indent level of the contained code lines.
collapseStyle
Section titled “collapseStyle”"github" | "collapsible-start" | "collapsible-end" | "collapsible-auto" Default:
'github' Allows to select one of the following collapsible section styles:
github: The default style, similar to the one used by GitHub. A summary line with an expand icon and the default textX collapsed linesis shown. When expanded, the summary line is replaced by the section’s code lines. It is not possible to re-collapse the section.collapsible-start: When collapsed, the summary line looks like thegithubstyle. However, when expanded, it remains visible above the expanded code lines, making it possible to re-collapse the section.collapsible-end: Same ascollapsible-start, but the summary line remains visible below the expanded code lines.collapsible-auto: Automatically selectscollapsible-startorcollapsible-endbased on the location of the collapsible section in the code block. Usescollapsible-startunless the section ends at the bottom of the code block, in which casecollapsible-endis used.
Styling
Section titled “Styling”This plugin adds a collapsibleSections object to the styleOverrides engine config option, allowing you to customize the visual appearance of the sections:
import { defineEcConfig } from 'astro-expressive-code'import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections'
export default defineEcConfig({ plugins: [pluginCollapsibleSections()], styleOverrides: { // You can optionally override the plugin's default styles here collapsibleSections: { closedBackgroundColor: '#68F', }, },})import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections'
/** @type {import('@astrojs/starlight/expressive-code').StarlightExpressiveCodeOptions} */export default { plugins: [pluginCollapsibleSections()], styleOverrides: { // You can optionally override the plugin's default styles here collapsibleSections: { closedBackgroundColor: '#68F', }, },}import createMDX from '@next/mdx'import rehypeExpressiveCode from 'rehype-expressive-code'import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections'
/** @type {import('rehype-expressive-code').RehypeExpressiveCodeOptions} */const rehypeExpressiveCodeOptions = { plugins: [pluginCollapsibleSections()], styleOverrides: { // You can optionally override the plugin's default styles here collapsibleSections: { closedBackgroundColor: '#68F', }, },}
/** @type {import('next').NextConfig} */const nextConfig = { reactStrictMode: true, pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],}
const withMDX = createMDX({ extension: /\.mdx?$/, options: { remarkPlugins: [], rehypePlugins: [ // The nested array structure is required to pass options // to a rehype plugin [rehypeExpressiveCode, rehypeExpressiveCodeOptions], ], },})
export default withMDX(nextConfig)Available style overrides
Section titled “Available style overrides”closedBackgroundColor
Section titled “closedBackgroundColor”({ theme }) => setAlpha(theme.colors['editor.foldBackground'], 0.2) || 'rgb(84 174 255 / 20%)' The background color of the summary line.
closedBorderColor
Section titled “closedBorderColor”({ theme }) => setAlpha(theme.colors['editor.foldBackground'], 0.5) || 'rgb(84 174 255 / 50%)' The border color of the summary line.
closedBorderWidth
Section titled “closedBorderWidth”The border width of the summary line.
Note: Despite the setting prefix closed, summary lines are also visible while the section is open when using any of the collapsible-* styles. This is the same for all closed* settings.
closedFontFamily
Section titled “closedFontFamily”The font family of the section summary line.
closedFontSize
Section titled “closedFontSize”The font size of the section summary line.
closedLineHeight
Section titled “closedLineHeight”The line height of the section summary line.
closedMargin
Section titled “closedMargin”The margin around the summary line.
closedPaddingBlock
Section titled “closedPaddingBlock”The block padding of the summary line.
closedTextColor
Section titled “closedTextColor”The text color of the section summary line.
collapseIcon
Section titled “collapseIcon”An inline SVG URL for the collapse icon.
Expects a string in the format url("data:image/svg+xml,..."), which can be generated from the contents of an SVG file using createInlineSvgUrl.
expandIcon
Section titled “expandIcon”An inline SVG URL for the expand icon.
Expects a string in the format url("data:image/svg+xml,..."), which can be generated from the contents of an SVG file using createInlineSvgUrl.
openBackgroundColor
Section titled “openBackgroundColor”The background color of expanded code lines when using the default github style.
openBackgroundColorCollapsible
Section titled “openBackgroundColorCollapsible”({ theme }) => setAlpha(theme.colors['editor.foldBackground'], 0.1) || 'rgb(84 174 255 / 10%)' The background color of expanded code lines when using any of the collapsible-* styles.
openBorderColor
Section titled “openBorderColor”The color of the border around expanded code lines.
openBorderWidth
Section titled “openBorderWidth”The width of the border around expanded code lines.
openMargin
Section titled “openMargin”The margin around open sections.
openPadding
Section titled “openPadding”The padding of open sections.