|
| 1 | +--- |
| 2 | +title: Line Anchors |
| 3 | +description: Add clickable anchor links to line numbers for easy reference and sharing. |
| 4 | +category: [Shiki, Markdown, MDX] |
| 5 | +--- |
| 6 | + |
| 7 | +<Showcase> |
| 8 | + |
| 9 | +```ts lineNumbers |
| 10 | +import { highlight } from "@/utils/shiki/highlight"; |
| 11 | +import { lineAnchors } from "@/utils/shiki/transformers/line-anchors"; |
| 12 | + |
| 13 | +const code = `console.log('Hello World')`; |
| 14 | +const highlighter = await highlight(); |
| 15 | +const html = highlighter.codeToHtml(code, { |
| 16 | + lang: "javascript", |
| 17 | + transformers: [lineAnchors()], |
| 18 | +}); |
| 19 | +``` |
| 20 | + |
| 21 | +</Showcase> |
| 22 | + |
| 23 | +The `lineAnchors` transformer adds clickable anchor links to line numbers. Each line gets an ID like `L1`, `L2`, etc. |
| 24 | + |
| 25 | +## Installation |
| 26 | + |
| 27 | +### shadcn/ui |
| 28 | + |
| 29 | +<CopyShadcnCommand name="shiki-line-anchors" /> |
| 30 | + |
| 31 | +### Manual |
| 32 | + |
| 33 | +1. Copy the `lineAnchors` transformer into your project: |
| 34 | + |
| 35 | +<ShowSource component="shiki-line-anchors" /> |
| 36 | + |
| 37 | +`shiki-line-anchors` styles are defined in the `shiki.css` file: |
| 38 | + |
| 39 | +<DocCard folder="shiki" document="highlighter" anchor="styles" /> |
| 40 | + |
| 41 | +2. Import the transformer in your `rehypeShiki` plugin: |
| 42 | + |
| 43 | +```ts title="Rehype Shiki Options" |
| 44 | +import { lineAnchors } from "@/utils/shiki/transformers/line-anchors"; |
| 45 | + |
| 46 | +const rehypeShikiOptions: RehypeShikiCoreOptions = { |
| 47 | + //... |
| 48 | + transformers: [lineAnchors()], |
| 49 | +}; |
| 50 | + |
| 51 | +export { rehypeShikiOptions }; |
| 52 | +``` |
| 53 | + |
| 54 | +## Usage |
| 55 | + |
| 56 | +Once enabled, users can: |
| 57 | + |
| 58 | +- Click line numbers to navigate to that line |
| 59 | +- Share URLs with line anchors: `yoursite.com/docs#L3` |
| 60 | +- Link to specific lines: `[See line 5](#L5)` |
| 61 | + |
| 62 | +The clicked line will be highlighted with a blue background and the URL will update to include the line anchor. |
0 commit comments