1
0
mirror of https://github.com/BoostIo/Boostnote synced 2025-12-13 09:46:22 +00:00

Automatic table of contents generation for Markdown

Adds table of contents for any Markdown note or
Markdown snippet.
Consequent generations update existing TOC.
Generated TOC is case sensitive to handle #2067

Shortcut : CommandOrControl+Alt+T
Menu : Edit/Generate/Update Markdown TOC
This commit is contained in:
Maciek
2018-08-10 21:39:59 +02:00
parent 79fb04126c
commit 7804a22984
6 changed files with 87 additions and 1 deletions

View File

@@ -0,0 +1,52 @@
/**
* @fileoverview Markdown table of contents generator
*/
import toc from 'markdown-toc'
import diacritics from 'diacritics-map'
import stripColor from 'strip-color'
/**
* @caseSensitiveSlugify Custom slugify function
* Same implementation that the original used by markdown-toc (node_modules/markdown-toc/lib/utils.js),
* but keeps original case to properly handle https://github.com/BoostIO/Boostnote/issues/2067
*/
function caseSensitiveSlugify (str) {
function replaceDiacritics (str) {
return str.replace(/[À-ž]/g, function (ch) {
return diacritics[ch] || ch
})
}
function getTitle (str) {
if (/^\[[^\]]+\]\(/.test(str)) {
var m = /^\[([^\]]+)\]/.exec(str)
if (m) return m[1]
}
return str
}
str = getTitle(str)
str = stripColor(str)
// str = str.toLowerCase() //let's be case sensitive
// `.split()` is often (but not always) faster than `.replace()`
str = str.split(' ').join('-')
str = str.split(/\t/).join('--')
str = str.split(/<\/?[^>]+>/).join('')
str = str.split(/[|$&`~=\\\/@+*!?({[\]})<>=.,;:'"^]/).join('')
str = str.split(/[。?!,、;:“”【】()〔〕[]﹃﹄“ ”‘’﹁﹂—…-~《》〈〉「」]/).join('')
str = replaceDiacritics(str)
return str
}
export function generate (currentValue, updateCallback) {
const TOC_MARKER = '<!-- toc -->'
if (!currentValue.includes(TOC_MARKER)) {
currentValue = TOC_MARKER + currentValue
}
updateCallback(toc.insert(currentValue, {slugify: caseSensitiveSlugify}))
}
export default {
generate
}