Help converting an HTML span to a Markdown directive #240
-
Hi there, In the past I have used unified to convert Markdown to HTML, and when I made a custom transformation, I used the hast properties (hName, hProperties, hChildren) in the mdast AST. However, I'm now tasked with converting HTML to Markdown and there doesn't seem to be a similar way to do this? My specifc problem is converting a span with class to a leaf directive: <p>My content and <span class="sidenote">my <b>sidenote</b></span>.</p> should become: My content and ::sidenote[my **sidenote**]. Where in this processor should I put my custom transformation, and what would it look like? import { unified } from 'unified';
import rehypeParse from 'rehype-parse';
import rehypeRemark from 'rehype-remark';
import remarkStringify from 'remark-stringify';
const file = await unified()
.use(rehypeParse)
.use(rehypeRemark)
.use(remarkStringify)
.process(`<p>My content and <span class="sidenote">my <b>sidenote</b></span>.</p>`)
console.log(String(file))
// current output is:
// My content and my **sidenote**. Thanks for any help. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hey! The h* fields are indeed also a good way to do this, the other way around, mdast -> hast. But, what is also possible, is to hook into the place where the conversion between the ASTs happens. They both support handlers:
There you would use |
Beta Was this translation helpful? Give feedback.
Hey!
The h* fields are indeed also a good way to do this, the other way around, mdast -> hast.
Such a thing does not exist hast -> mdast.
But, what is also possible, is to hook into the place where the conversion between the ASTs happens.
remark-rehype
andrehype-remark
.They both support handlers:
There you would use
span
as a key, and write a handler that generates a text directive: https://github.com/syntax-tree/mdast-util-directive#textdirective.