From 39c61f62b8ee2eb599d39500f5ff55cd995aa725 Mon Sep 17 00:00:00 2001 From: btea <2356281422@qq.com> Date: Sun, 24 Nov 2024 15:30:58 +0800 Subject: [PATCH] feat: markdown file inclusion support specify title --- docs/en/guide/markdown.md | 34 +++++++++++++++++++++++++++++++ src/node/utils/processIncludes.ts | 20 +++++++++++++++--- 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/docs/en/guide/markdown.md b/docs/en/guide/markdown.md index dd577fe1..f85c9524 100644 --- a/docs/en/guide/markdown.md +++ b/docs/en/guide/markdown.md @@ -897,6 +897,40 @@ You can also use a [VS Code region](https://code.visualstudio.com/docs/editor/co Note that this does not throw errors if your file is not present. Hence, when using this feature make sure that the contents are being rendered as expected. ::: +You can also specify a title: + +**Input** + +```md +# Docs + +## Basics + + +``` + +**Part file** (`parts/basics.md`) + +```md +Some getting started stuff. + +### Configuration + +Can be created using `.foorc.json`. +``` + +**Equivalent code** + +```md +# Docs + +## Basics + +### Configuration + +Can be created using `.foorc.json`. +``` + ## Math Equations This is currently opt-in. To enable it, you need to install `markdown-it-mathjax3` and set `markdown.math` to `true` in your config file: diff --git a/src/node/utils/processIncludes.ts b/src/node/utils/processIncludes.ts index 067bb110..315a34a2 100644 --- a/src/node/utils/processIncludes.ts +++ b/src/node/utils/processIncludes.ts @@ -12,19 +12,21 @@ export function processIncludes( includes: string[] ): string { const includesRE = //g - const regionRE = /(#[\w-]+)/ + const regionRE = /[^{#](#[\w-]+)/ const rangeRE = /\{(\d*),(\d*)\}$/ + const titleRE = /(\{#+\s?[\w\s]+\})/ return src.replace(includesRE, (m: string, m1: string) => { if (!m1.length) return m const range = m1.match(rangeRE) const region = m1.match(regionRE) + const title = m1.match(titleRE) - const hasMeta = !!(region || range) + const hasMeta = !!(region || range || title) if (hasMeta) { - const len = (region?.[0].length || 0) + (range?.[0].length || 0) + const len = (region?.[0].length || 0) + (range?.[0].length || 0) + (title?.[0].length || 0) m1 = m1.slice(0, -len) // remove meta info from the include path } @@ -54,6 +56,18 @@ export function processIncludes( .join('\n') } + if (title) { + const titleName = title[0].slice(1, -1).trim() + const lines = content.split(/\r?\n/) + const start = lines.findIndex((line) => line === titleName) + const end = lines.findIndex((line) => /#+\s?[\w\s]+/.test(line) && line !== titleName) + if (end === -1) { + content = lines.slice(start).join('\n') + } else { + content = lines.slice(start, end).join('\n') + } + } + if (!hasMeta && path.extname(includePath) === '.md') { content = matter(content).content }