2019-08-09 12:42:07 +00:00
|
|
|
'use strict'
|
|
|
|
/* global hexo */
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Add Link button next to a heading
|
2024-06-07 12:38:33 +00:00
|
|
|
* based on https://github.com/hexojs/hexo-renderer-marked/blob/master/lib/renderer.js
|
2019-08-09 12:42:07 +00:00
|
|
|
*/
|
|
|
|
|
2024-06-07 12:38:33 +00:00
|
|
|
const { slugize, stripHTML, unescapeHTML: unescape } = require('hexo-util')
|
2019-12-24 04:38:02 +00:00
|
|
|
|
|
|
|
const anchorId = (str, transformOption) => {
|
2024-06-07 12:38:33 +00:00
|
|
|
return slugize(stripHTML(unescape(str)).trim(), { transform: transformOption });
|
2019-12-24 04:38:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
hexo.extend.filter.register('marked:renderer', function (renderer) {
|
|
|
|
const { config } = this
|
|
|
|
renderer.heading = function (text, level) {
|
2024-06-07 12:38:33 +00:00
|
|
|
const { modifyAnchors } = config.marked
|
|
|
|
const transformOption = modifyAnchors;
|
|
|
|
let id = anchorId(text, transformOption)
|
|
|
|
const headingId = {};
|
2019-12-24 04:38:02 +00:00
|
|
|
|
|
|
|
// Add a number after id if repeated
|
|
|
|
if (headingId[id]) {
|
|
|
|
id += `-${headingId[id]++}`
|
|
|
|
} else {
|
|
|
|
headingId[id] = 1
|
|
|
|
}
|
|
|
|
|
|
|
|
// add headerlink
|
2021-11-30 08:18:07 +00:00
|
|
|
return `<h${level} id="${id}">${text} <a href="#${id}" class="headerlink" title="${stripHTML(text)}">§</a></h${level}>`
|
2019-12-24 04:38:02 +00:00
|
|
|
}
|
2019-08-09 12:42:07 +00:00
|
|
|
})
|