File size: 1,816 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// From: https://github.com/shikijs/shiki/blob/main/packages/transformers/src/transformers/meta-highlight-word.ts
// MIT License
import type { ShikiTransformer } from "shiki"

function parseMetaHighlightWords(meta: string): string[] {
  if (!meta) return []

  // Remove any title="..." or title='...' content first
  const metaWithoutTitle = meta.replace(/title=(["'])(.*?)\1/g, "")

  // https://regex101.com/r/BHS5fd/1
  const match = Array.from(metaWithoutTitle.matchAll(/\/((?:\\.|[^/])+)\//g))

  return (
    match
      // Escape backslashes
      .map((v) => v[1].replace(/\\(.)/g, "$1"))
  )
}

export interface TransformerMetaWordHighlightOptions {
  /**
   * Class for highlighted words
   *
   * @default 'highlighted-word'
   */
  className?: string
}

/**
 * Allow using `/word/` in the code snippet meta to mark highlighted words.
 */
export function transformerMetaWordHighlight(
  options: TransformerMetaWordHighlightOptions = {},
): ShikiTransformer {
  const { className = "highlighted-word" } = options

  return {
    name: "@shikijs/transformers:meta-word-highlight",
    preprocess(code, options) {
      if (!this.options.meta?.__raw) return

      const words = parseMetaHighlightWords(this.options.meta.__raw)
      options.decorations ||= []
      for (const word of words) {
        const indexes = findAllSubstringIndexes(code, word)
        for (const index of indexes) {
          options.decorations.push({
            start: index,
            end: index + word.length,
            properties: {
              class: className,
            },
          })
        }
      }
    },
  }
}

function findAllSubstringIndexes(str: string, substr: string): number[] {
  const indexes = []
  let i = -1
  while ((i = str.indexOf(substr, i + 1)) !== -1) indexes.push(i)
  return indexes
}