Skip to content

Instantly share code, notes, and snippets.

@rodneyrehm
Created August 12, 2016 09:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodneyrehm/4feec9af8a8635f7de7cb1754f146a39 to your computer and use it in GitHub Desktop.
Save rodneyrehm/4feec9af8a8635f7de7cb1754f146a39 to your computer and use it in GitHub Desktop.
markdown-it-adjust-heading-levels
<!-- { firstLevel: 3 } -->
<h3>First <em>Level</em> headline</h3>
<p>first level content</p>
<h4>Second Level headline alpha</h4>
<p>second level content alpha</p>
<h5>Third Level headline alpha</h5>
<p>third level content alpha</p>
<h4>Second Level headline bravo</h4>
<p>second level content bravo</p>
<h5>Deep Third</h5>
<p>content</p>
<h6>Deep Fourth</h6>
<p>content</p>
<h6>Deep Fifth</h6>
<p>content</p>
<h6>Deep Sixth</h6>
<p>content</p>
<p>####### Deep Seventh #######</p>
'use strict';
var markdownIt = require('markdown-it');
var fs = require('fs');
var source = fs.readFileSync('./test.md', {encoding: 'utf8'});
function getHeadingLevel(tagName) {
if (tagName[0].toLowerCase() === 'h') {
tagName = tagName.slice(1);
}
return parseInt(tagName, 10);
}
function adjustHeadingLevel(md, options) {
var firstLevel = options.firstLevel;
if (typeof firstLevel === 'string') {
firstLevel = getHeadingLevel(firstLevel);
}
if (!firstLevel || isNaN(firstLevel)) {
return;
}
var levelOffset = firstLevel - 1;
if (levelOffset < 1 || levelOffset > 6) {
return;
}
md.core.ruler.push("adjust-heading-levels", function(state) {
var tokens = state.tokens
for (var i = 0; i < tokens.length; i++) {
if (tokens[i].type !== "heading_close") {
continue
}
var headingOpen = tokens[i - 2];
// var heading_content = tokens[i - 1];
var headingClose = tokens[i];
// we could go deeper with <div role="heading" aria-level="7">
// see http://w3c.github.io/aria/aria/aria.html#aria-level
// but clamping to a depth of 6 should suffice for now
var currentLevel = getHeadingLevel(headingOpen.tag);
var tagName = 'h' + Math.min(currentLevel + levelOffset, 6);
headingOpen.tag = tagName;
headingClose.tag = tagName;
}
});
}
var result = markdownIt({
html: true,
linkify: true,
typography: true,
})
.use(adjustHeadingLevel, { firstLevel: 3 })
.render(source);
console.log(result);

First Level headline

first level content

Second Level headline alpha

second level content alpha

Third Level headline alpha

third level content alpha

Second Level headline bravo

second level content bravo

Deep Third

content

Deep Fourth

content

Deep Fifth

content

Deep Sixth

content

####### Deep Seventh #######

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment