-
Working on writing a md parser that outputs HTML that is compliant with the tufte-css style sheet. One thing I'm puzzled on right now is how to wrap sections in # Heading A
blah...
## Heading B
blah...
### Heading C
blah ...
## Heading D
blah ...
To use the HTML section tags per both tufte-css and the HTML spec sheet you'd want to take the above and render it as: <article>
<h1>Heading A</h1>
<p>blah...</p>
<section>
<h2>Heading B</h2>
<p>blah...</p>
<section>
<h3>Heading C</h3>
<p>blah...</p>
</section>
</section>
<section>
<h2>Heading D</h2>
<p>blah...</p>
</section>
</article> We can ignore the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can create an extension that finds the text for each section and renders it with the proper tags surrounding it. Here is one solution. It probably doesn't work in every situation but it should be a good start. import { Marked } from './src/marked.js';
// The sectionLevel will help us prevent matching the same header multiple times.
let sectionLevel = 0;
// Creating regular expressions is expensive so we create them once.
// Create 7 sections since that is the maximum heading level.
const sectionRegexps = new Array(7).fill().map((e, i) => new RegExp(`^(#{${i + 1}} )[^]*?(?:\\n(?=\\1)|$)`));
const sectionExtension = {
extensions: [{
name: 'sectionBlock',
level: 'block',
start(src) {
// Match when # is at the beginning of a line.
return src.match(/^#/m)?.index;
},
tokenizer(src) {
const match = src.match(sectionRegexps[sectionLevel]);
if (!match) {
return;
}
sectionLevel++;
// Tokenize text inside the section.
// Only add sectionBlock token for headers one level up from current level.
const tokens = this.lexer.blockTokens(match[0]);
sectionLevel--;
return {
type: 'sectionBlock',
raw: match[0],
level: sectionLevel + 1,
tokens
};
},
renderer(token) {
const tag = token.level === 1 ? 'article' : 'section';
return `<${tag}>\n${this.parser.parse(token.tokens)}</${tag}>\n`;
}
}]
};
const marked = new Marked(sectionExtension);
const md = `
# Heading A
blah...
## Heading B
blah...
### Heading C
blah ...
## Heading D
blah ...
`;
console.log(marked.parse(md)); outputs: <article>
<h1 id="heading-a">Heading A</h1>
<p>blah...</p>
<section>
<h2 id="heading-b">Heading B</h2>
<p>blah...</p>
<section>
<h3 id="heading-c">Heading C</h3>
<p>blah ...</p>
</section>
</section>
<section>
<h2 id="heading-d">Heading D</h2>
<p>blah ...</p>
</section>
</article> |
Beta Was this translation helpful? Give feedback.
You can create an extension that finds the text for each section and renders it with the proper tags surrounding it.
Here is one solution. It probably doesn't work in every situation but it should be a good start.