rehype-markdown-offsets
v1.0.0
Published
rehype plugin to annotate elements with source start/end offsets
Maintainers
Readme
rehype-markdown-offsets
Add Markdown/MDX source offsets to HTML elements for precise selection mapping.
What is this?
This package is a unified/rehype plugin that attaches the original Markdown or MDX source positions to HTML elements via data-start and data-end attributes.
Normally, once Markdown/MDX is compiled to HTML, you lose the mapping back to the original source text. This plugin restores that mapping by attaching source offsets directly to elements, enabling features like:
- highlight-to-reply in chatbot applications
- mapping selections back to Markdown for editors
- precise synchronization between rendered view and source code
Installation
npm i rehype-markdown-offsetsUsage
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkMdx from 'remark-mdx';
import remarkRehype from 'remark-rehype';
import rehypeMarkdownOffsets from 'rehype-markdown-offsets';
import rehypeStringify from 'rehype-stringify';
const mdx = `
Hello **world** and [friends](#).
`;
const html = await unified()
.use(remarkParse)
.use(remarkMdx)
.use(remarkRehype, { allowDangerousHtml: true })
.use(rehypeMarkdownOffsets)
.use(rehypeStringify)
.process(mdx);
console.log(String(html));Output Example
<p data-start="0" data-end="29">
Hello
<strong data-start="6" data-end="14">world</strong>
and
<a href="#" data-start="15" data-end="29">friends</a>.
</p>By default this adds data-start and data-end attributes to element nodes that have numeric position.start.offset and position.end.offset. These offsets correspond to absolute character indices in the original Markdown/MDX source.
Options
rehypeMarkdownOffsets({
startAttribute: 'data-start', // default
endAttribute: 'data-end', // default
filter: (node) => true, // annotate only matching elements
overwrite: true, // overwrite attributes if already present
})