Shiki 代码高亮测试
为了让页面本身更轻,这里不再为每个示例放置“源码 / 预览”两个标签页。需要看原始 Markdown 时,可以在文章信息弹窗中预览同目录下的 index.md
行内代码
Shiki 支持给行内代码加语言标记。普通行内代码保持原样;需要按语言高亮时,在内容前写 {language}。
- Plain:
printf("Hello, World") - Python:
print("Hello, World") - JavaScript:
console.log("Hello, World") - HTML:
<h1>Hello, World!</h1> - Rust:
fn main() { println!("Hello, World!"); } - Shell:
echo "Hello, World!"
代码块
高亮器还可以读取代码块标题,例如下面的 fibonacci.py。def fibonacci(n): fib_sequence = [0, 1] while len(fib_sequence) < n: fib_sequence.append(fib_sequence[-1] + fib_sequence[-2]) return fib_sequence# Example usageprint(fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
排版边界
测试1: 长代码
## One LineSo, so you think you can tell Heaven from Hell blue skies from pain Can you tell a green field from a cold steel rail? A smile from a veil? Do you think you can tell? And did they get you to trade your heroes for ghosts? Hot ashes for trees? Hot air for a cool breeze? Cold comfort for change? And did you exchange a walk on part in the war for a lead role in a cage? How I wish, how I wish you were here We're just two lost souls swimming in a fish bowl year after year Running over the same old ground What have you found? The same old fears Wish you were here---## Multiple LinesSo, so you think you can tellHeaven from Hellblue skies from painCan you tell a green fieldfrom a cold steel rail?A smile from a veil?Do you think you can tell?And did they get you to tradeyour heroes for ghosts?Hot ashes for trees?Hot air for a cool breeze?Cold comfort for change?And did you exchangea walk on part in the warfor a lead role in a cage?How I wish, how I wish you were hereWe're just two lost souls swimming in a fish bowlyear after yearRunning over the same old groundWhat have you found?The same old fearsWish you were here测试2: 列表
如果缩进不正确,代码块会脱离列表层级。
- 这是一个列表项
这是一个嵌套子项,下面紧跟代码块
def hello_world(): print("hello")
Transformer 标记
Shiki 的 Transformer 可以根据注释标记给代码生成额外样式。比如在注释中添加 [!code --],对应代码行会被标记为删除;添加 [!code ++],对应代码行会被标记为新增。类型 标记 Diff-Remove print(A) # [!code --]Diff-Add print(A) # [!code ++]Highlight print(A) # [!code highlight]Word # [!code word:Hello]Focus print(A) # [!code focus]ErrorLevel print(A) # [!code error]
更多标记可以参考 @shikijs/transformers | Shiki。
Diff
console.log("hewwo");console.log("hello");console.log("goodbye");Highlight
console.log("Not highlighted");console.log("Highlighted");console.log("Not highlighted");Word Highlight
const message = "Hello World";console.log(message); // prints Hello WorldFocus
console.log("Not focused");console.log("Focused");console.log("Not focused");Error Level
console.log("No errors or warnings");console.error("Error");console.warn("Warning");console.log("Info");
