Video failed to load

Code Block Examples

1997 words
10 minutes
Code Block Examples
Code Block Examples

This article explores how to display code blocks with Expressive Code. The examples are based on its official documentation, where you can find more details.

Expressive Code#

Syntax Highlighting#

Syntax Highlighting

Regular Syntax Highlighting#

console.log('此代码有语法高亮!')

Rendering ANSI Escape Sequences#

Terminal window
Standard ANSI colors:
- Dimmed: Black Red Green Yellow Blue Magenta Cyan White
- Foreground: Black Red Green Yellow Blue Magenta Cyan White
- Background: Black Red Green Yellow Blue Magenta Cyan White
- Reversed: Black Red Green Yellow Blue Magenta Cyan White
8-bit colors (showing colors 160-171 as an example):
- Dimmed: 160 161 162 163 164 165 166 167 168 169 170 171
- Foreground: 160 161 162 163 164 165 166 167 168 169 170 171
- Background: 160 161 162 163 164 165 166 167 168 169 170 171
- Reversed: 160 161 162 163 164 165 166 167 168 169 170 171
24-bit colors (full RGB):
- Dimmed: ForestGreen - RGB(34,139,34) RebeccaPurple - RGB(102,51,153)
- Foreground: ForestGreen - RGB(34,139,34) RebeccaPurple - RGB(102,51,153)
- Background: ForestGreen - RGB(34,139,34) RebeccaPurple - RGB(102,51,153)
- Reversed: ForestGreen - RGB(34,139,34) RebeccaPurple - RGB(102,51,153)
Font styles:
- Default
- Bold
- Dimmed
- Italic
- Underline
- Reversed
- Strikethrough

Editor and Terminal Frames#

Editor and Terminal Frames

Code Editor Frames#

my-test-file.js
console.log('标题属性示例')

src/content/index.html
<div>文件名注释示例</div>

Terminal Frames#

Terminal window
echo "此终端框架没有标题"

PowerShell 终端示例
Write-Output "这个有标题!"

Overriding Frame Types#

echo "看,没有框架!"

PowerShell Profile.ps1
# 如果不覆盖,这将是一个终端框架
function Watch-Tail { Get-Content -Tail 20 -Wait $args }
New-Alias tail Watch-Tail

Text and Line Markers#

Text and Line Markers

Marking Entire Lines and Line Ranges#

// 第1行 - 通过行号定位
// 第2行
// 第3行
// 第4行 - 通过行号定位
// 第5行
// 第6行
// 第7行 - 通过范围 "7-8" 定位
// 第8行 - 通过范围 "7-8" 定位

Choosing a Line Marker Type (mark, ins, del)#

line-markers.js
function demo() {
console.log('此行标记为已删除')
// 此行和下一行标记为已插入
console.log('这是第二个插入行')
return '此行使用中性默认标记类型'
}

Adding Labels to Line Markers#

labeled-line-markers.jsx
<button
role="button"
{...props}
value={value}
className={buttonClassName}
disabled={disabled}
active={active}
>
{children &&
!active &&
(typeof children === 'string' ? <span>{children}</span> : children)}
</button>

Adding Long Labels on Separate Lines#

labeled-line-markers.jsx
<button
role="button"
{...props}
value={value}
className={buttonClassName}
disabled={disabled}
active={active}
>
{children &&
!active &&
(typeof children === 'string' ? <span>{children}</span> : children)}
</button>

Using Diff-like Syntax#

此行将标记为已插入
此行将标记为已删除
这是常规行

--- a/README.md
+++ b/README.md
@@ -1,3 +1,4 @@
+this is an actual diff file
-all contents will remain unmodified
no whitespace will be removed either

Combining Syntax Highlighting with Diff-like Syntax#

function thisIsJavaScript() {
// 整个块都会以 JavaScript 高亮显示,
// 并且我们仍然可以为其添加 diff 标记!
console.log('要删除的旧代码')
console.log('新的闪亮代码!')
}

Marking Individual Text Within a Line#

function demo() {
// 标记行内的任何给定文本
return '支持给定文本的多个匹配项';
}

Regular Expressions#

console.log('单词 yes 和 yep 将被标记。')

Escaping Forward Slashes#

Terminal window
echo "Test" > /home/test.txt

Choosing an Inline Marker Type (mark, ins, del)#

function demo() {
console.log('这些是插入和删除的标记类型');
// return 语句使用默认标记类型
return true;
}

Word Wrap#

Word Wrap

Configuring Word Wrap Per Block#

// 启用换行的示例
function getLongString() {
return '这是一个非常长的字符串,除非容器极宽,否则很可能无法适应可用空间'
}

// wrap=false 的示例
function getLongString() {
return '这是一个非常长的字符串,除非容器极宽,否则很可能无法适应可用空间'
}

Configuring Wrapped Line Indentation#

// preserveIndent 示例(默认启用)
function getLongString() {
return '这是一个非常长的字符串,除非容器极宽,否则很可能无法适应可用空间'
}

// preserveIndent=false 的示例
function getLongString() {
return '这是一个非常长的字符串,除非容器极宽,否则很可能无法适应可用空间'
}

Collapsible Sections#

Collapsible Sections

5 collapsed lines
// 所有这些样板设置代码将被折叠
import { someBoilerplateEngine } from '@example/some-boilerplate'
import { evenMoreBoilerplate } from '@example/even-more-boilerplate'
const engine = someBoilerplateEngine(evenMoreBoilerplate())
// 这部分代码默认可见
engine.doSomething(1, 2, 3, calcFn)
function calcFn() {
// 您可以有多个折叠部分
3 collapsed lines
const a = 1
const b = 2
const c = a + b
// 这将保持可见
console.log(`计算结果: ${a} + ${b} = ${c}`)
return c
}
4 collapsed lines
// 直到块末尾的所有代码将再次被折叠
engine.closeConnection()
engine.freeMemory()
engine.shutdown({ reason: '示例样板代码结束' })

Line Numbers#

Line Numbers

Showing Line Numbers Per Block#

// 此代码块将显示行号
console.log('来自第2行的问候!')
console.log('我在第3行')

// 此块禁用行号
console.log('你好?')
console.log('抱歉,你知道我在第几行吗?')

Changing the Starting Line Number#

console.log('来自第5行的问候!')
console.log('我在第6行')

Tabbed Code Blocks#

Powered by rehype-code-group, using the same syntax as VitePress code groups: wrap multiple code blocks in ::: code-group labels=[...] to combine them into a set of tabs.

Note

The comma-separated labels in labels=[...] correspond to the blocks in order. The space between ::: and code-group is required.

Basic Usage#

::: code-group labels=[code.js, code.py, code.html]
```js
export function greet(name) {
return `Hello, ${name}!`;
}
```
```py
def greet(name):
return f"Hello, {name}!"
```
```html
<p>Hello, world!</p>
```
:::

Rendered Result:

export function greet(name) {
return `Hello, ${name}!`;
}

Using Emoji in Tab Labels#

Labels support emoji shortcodes, which are converted to emoji at build time:

::: code-group labels=[:package: npm, :package: pnpm, :yarn: yarn]
Terminal window
npm create astro@latest

Combining with Other Code Block Features#

Blocks inside a group remain regular Expressive Code blocks. Titles, line numbers, line markers, collapsing, terminal frames, and other features work as usual.

astro.config.mjs
export default {
theme: "firefly",
codeGroup: true,
};

More Than Code Blocks#

Tabs can contain any content, such as text, lists, or images:

This is an ordinary paragraph.

Tip

The tab bar is generated at build time and initially opens the first tab. Switch tabs with the mouse or the ←, →, Home, and End keys.

Using Tabs in Admonitions (MDX Components)#

Both ::: code-group and Docusaurus-style admonitions such as ::: tip use ::: containers. Because micromark-directive requires nested containers to use different numbers of colons, ::: code-group cannot be nested inside admonitions such as ::: tip; the entire block will fail to render.

Use the MDX TabGroup component instead. MDX components bypass ::: directive parsing, work inside or outside admonitions, and make it easier to add more UI components later. Change the extension to .mdx and import components from the shared @/components/firefly-mdx entry point:

import { TabGroup } from "@/components/firefly-mdx";
:::tip
<TabGroup labels={["test.js", "test.py"]} client:load>
```js
console.log(1)
```
```py
print("hello world")
```
</TabGroup>
:::
Tip
  • The labels array assigns a label to each code block in the same order
  • Use client:load to enable interactive tab switching

Support & Share

If this article helped you, please share or support!

Sponsor
Code Block Examples
https://docs.bingyun.vip/en/posts/code-examples/
Author
BingYun
Published at
1970-01-06
Profile Image of the Author
BingYun
Hello, I'm BingYun
Tags
Table of Contents