Attach location to Rehype's HTML elements from Remark #97
-
Hi, I hope this is the right place to ask questions. I'll explain my situation briefly first before the specific question: I'm working on a markdown editor, so I use remark, remark-rehype and rehype to generate a HTML preview from markdown content in the editor. Now I'd like to sync the scroll between the editor (markdown) and the preview (HTML). To do this, I believe I need to know which markdown line generates which HTML element. My question is: is it possible with some plugins in the unified ecosystem yet? I strongly believe it's possible, but I just don't know if there are plugins for that yet. So far I found none but the plugins are spread across projects so I'm not sure if I missed any. To give an example, my goal is, given a markdown like this: first
second I should have the following HTML: <p data-line="1">first</p>
<p data-line="2">second</p> |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 6 replies
-
Welcome! An example with positional information: const report = require('vfile-reporter')
const unified = require('unified')
const markdown = require('remark-parse')
const remark2rehype = require('remark-rehype')
unified()
.use(markdown)
.use(remark2rehype)
// stringify HAST directly
.use(function () {this.Compiler = (tree) => JSON.stringify(tree, null, 4)})
.process(`
# test
1. one
2. two
`, function (err, file) {
console.error(report(err || file))
console.log(String(file))
}) note the positions align with where content appeared in the markdown, allowing mapping. |
Beta Was this translation helpful? Give feedback.
-
1 year later.. I should have make this a npm instead of code it directly into my project :(( now I need it on another project and the old code is hardly usable... |
Beta Was this translation helpful? Give feedback.
-
Here's a working example: https://svelte.dev/repl/78d2e0ef1f8c4e678f796c0e3f5a0c73?version=4.2.8 |
Beta Was this translation helpful? Give feedback.
Welcome!
Assuming https://github.com/remarkjs/remark-rehype (wrapper around https://github.com/syntax-tree/mdast-util-to-hast) is being used.
The position information of the node should be carried through from MDAST to HAST.
Which could be used to set the position in the HAST/HTML based of the cursor position in the Markdown/MDAST.
An example with positional information: