|
| 1 | +import type { ShikiTransformer } from '@shikijs/types' |
| 2 | +import type { Element } from 'hast' |
| 3 | + |
| 4 | +export interface TransformerRenderIndentGuidesOptions { |
| 5 | + indent?: number |
| 6 | +} |
| 7 | + |
| 8 | +/** |
| 9 | + * Render indentations as separate tokens. |
| 10 | + * Apply with CSS, it can be used to render indent guides visually. |
| 11 | + */ |
| 12 | +export function transformerRenderIndentGuides( |
| 13 | + options: TransformerRenderIndentGuidesOptions = {}, |
| 14 | +): ShikiTransformer { |
| 15 | + return { |
| 16 | + name: '@shikijs/transformers:render-indent-guides', |
| 17 | + code(hast) { |
| 18 | + let { indent = 2 } = options |
| 19 | + |
| 20 | + const match = this.options.meta?.__raw?.match(/\{indent:(\d+|false)\}/) |
| 21 | + if (match) { |
| 22 | + if (match[1] === 'false') { |
| 23 | + return hast |
| 24 | + } |
| 25 | + indent = Number(match[1]) |
| 26 | + } |
| 27 | + const indentRegex = new RegExp(` {${indent}}| {0,${indent - 1}}\t| {1,}$`, 'g') |
| 28 | + |
| 29 | + const emptyLines: [Element, number][] = [] |
| 30 | + let level = 0 |
| 31 | + |
| 32 | + for (const line of hast.children) { |
| 33 | + if (line.type !== 'element') { |
| 34 | + continue |
| 35 | + } |
| 36 | + |
| 37 | + const first = line.children[0] |
| 38 | + if (first?.type !== 'element' || first?.children[0]?.type !== 'text') { |
| 39 | + emptyLines.push([line, level]) |
| 40 | + continue |
| 41 | + } |
| 42 | + |
| 43 | + const text = first.children[0] |
| 44 | + const blanks = text.value.split(/[^ \t]/, 1)[0] |
| 45 | + |
| 46 | + const ranges: [number, number][] = [] |
| 47 | + for (const match of blanks.matchAll(indentRegex)) { |
| 48 | + const start = match.index |
| 49 | + const end = start + match[0].length |
| 50 | + ranges.push([start, end]) |
| 51 | + } |
| 52 | + |
| 53 | + for (const [line, level] of emptyLines) { |
| 54 | + line.children.unshift(...Array.from({ length: Math.min(ranges.length, level + 1) }, (_, i) => ({ |
| 55 | + type: 'element', |
| 56 | + tagName: 'span', |
| 57 | + properties: { |
| 58 | + class: 'indent', |
| 59 | + style: `--indent-offset: ${i * indent}ch;`, |
| 60 | + }, |
| 61 | + children: [], |
| 62 | + } satisfies Element))) |
| 63 | + } |
| 64 | + emptyLines.length = 0 |
| 65 | + level = ranges.length |
| 66 | + |
| 67 | + if (ranges.length) { |
| 68 | + line.children.unshift( |
| 69 | + ...ranges.map(([start, end]) => ({ |
| 70 | + type: 'element', |
| 71 | + tagName: 'span', |
| 72 | + properties: { |
| 73 | + class: 'indent', |
| 74 | + }, |
| 75 | + children: [{ |
| 76 | + type: 'text', |
| 77 | + value: text.value.slice(start, end), |
| 78 | + }], |
| 79 | + } satisfies Element)), |
| 80 | + ) |
| 81 | + text.value = text.value.slice(ranges.at(-1)![1]) |
| 82 | + } |
| 83 | + } |
| 84 | + return hast |
| 85 | + }, |
| 86 | + } |
| 87 | +} |
0 commit comments