Skip to content

Expressive Code

Code blocks in Starlight are powered by the Expressive Code engine. You do not need to import a special component; standard Markdown code fences are automatically upgraded with copy buttons, syntax highlighting, file titles, line markers, and visual diffs.

Enhance technical code snippets with syntax highlighting and line annotations:

  1. Open Code Fence: Use triple backticks followed by the programming language identifier (e.g., javascript, yaml).
  2. Add Line Markers: Append curly brace line selectors like {2} to highlight specific rows.
  3. Verify Output: Ensure your build compiler parses the snippet correctly.

Explore the live specimens, the raw Markdown required to build them, and instructions for authoring code blocks inside Sveltia CMS.

Below are two common code block use cases: highlighting specific lines in a named file, and showing a code diff (additions and deletions).


astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
export default defineConfig({
site: 'https://docs.timothyjohnsonwrites.com',
trailingSlash: 'always',
});
package.json
"dependencies": {
"astro": "^3.0.0",
"astro": "^4.0.0",
"astro-auto-import": "^0.4.2"
}

When adding code blocks to this knowledge base, adhere to the following stylistic rules:

  • Always Specify a Language: Never leave a code block language blank. Use text or plaintext if there is no specific syntax to highlight. This ensures accessibility and proper rendering.
  • Use File Titles Contextually: If the user is expected to copy-paste the code into a specific file, include title="filename.ext" so they know exactly where it belongs.
  • Highlight What Changed: If you are showing a massive 50-line configuration file just to demonstrate a 2-line change, use line highlights (e.g., {24-25}) so the reader doesn’t have to hunt for the relevant information.
  • Use Diff Syntax for Upgrades: When writing migration guides or troubleshooting articles, use the diff language with - (red) and + (green) symbols to clearly demonstrate what the user must delete and what they must add.