Line Anchors

Add clickable anchor links to line numbers for easy reference and sharing.

ShikiMarkdownMDX

Preview

.ts
import { highlight } from "@/utils/shiki/highlight";
import { lineAnchors } from "@/utils/shiki/transformers/line-anchors";

const code = `console.log('Hello World')`;
const highlighter = await highlight();
const html = highlighter.codeToHtml(code, {
  lang: "javascript",
  transformers: [lineAnchors()],
});

The lineAnchors transformer adds clickable anchor links to line numbers. Each line gets an ID like L1, L2, etc.

Installation

shadcn/ui

shadcn/ui Command
pnpm dlx shadcn@latest add https://code-blocks.pheralb.dev/r/shiki-line-anchors.json

Manual

  1. Copy the lineAnchors transformer into your project:
.ts
import type { ShikiTransformer } from "shiki";

/**
 * Transformer to add anchor links to line numbers
 * Allows users to link to specific lines in code blocks
 * Usage: Automatically works with lineNumbers transformer
 * Result: Each line gets an id like "L1", "L2", etc.
 */
const lineAnchors = (): ShikiTransformer => {
  return {
    name: "LineAnchors",
    line(node, line) {
      // Add id attribute to each line for anchor linking
      node.properties.id = `L${line}`;
      
      // Add data attribute for styling targeted lines
      node.properties["data-line"] = line;
    },
    pre(node) {
      // Add class to enable anchor styling
      const existingClass = node.properties.class;
      if (Array.isArray(existingClass)) {
        existingClass.push("shiki-line-anchors");
      } else if (typeof existingClass === "string") {
        node.properties.class = `${existingClass} shiki-line-anchors`;
      } else {
        node.properties.class = "shiki-line-anchors";
      }
    },
  };
};

export { lineAnchors };

shiki-line-anchors styles are defined in the shiki.css file:

shikiShiki Highlighter#styles

The main highlighter utility to render syntax highlighted code.

  1. Import the transformer in your rehypeShiki plugin:
Rehype Shiki Options
import { lineAnchors } from "@/utils/shiki/transformers/line-anchors";

const rehypeShikiOptions: RehypeShikiCoreOptions = {
  //...
  transformers: [lineAnchors()],
};

export { rehypeShikiOptions };

Usage

Once enabled, users can:

  • Click line numbers to navigate to that line
  • Share URLs with line anchors: yoursite.com/docs#L3
  • Link to specific lines: [See line 5](#L5)

The clicked line will be highlighted with a blue background and the URL will update to include the line anchor.