feat(md): optionally strip #region markers

if `stripMarkersFromSnippets` is set, `<<<` snippets will strip out all
region markers:

```file.ts
// #region A
// #region B
console.log("Hello, World!");
// #endregion
// #endregion
```

<<< file.ts#A

...would not include "#region B" anymore
pull/5014/head
Miroma 6 days ago
parent 6e8827146e
commit 5bcaef03ea
No known key found for this signature in database

@ -147,6 +147,11 @@ export interface MarkdownOptions extends MarkdownItAsyncOptions {
* @default 'Copy Code'
*/
codeCopyButtonTitle?: string
/**
* Remove all #region markers when including snippets
* @default false
*/
stripMarkersFromSnippets?: boolean
/* ==================== Markdown It Plugins ==================== */
@ -281,7 +286,7 @@ export async function createMarkdownRenderer(
codeCopyButtonTitle,
languageLabel: options.languageLabel
})
snippetPlugin(md, srcDir)
snippetPlugin(md, srcDir, options.stripMarkersFromSnippets)
containerPlugin(md, options.container)
imagePlugin(md, options.image)
linkPlugin(

@ -126,7 +126,11 @@ export function findRegions(lines: string[], regionName: string) {
return returned
}
export const snippetPlugin = (md: MarkdownItAsync, srcDir: string) => {
export const snippetPlugin = (
md: MarkdownItAsync,
srcDir: string,
stripMarkersFromSnippets = false
) => {
const parser: RuleBlock = (state, startLine, endLine, silent) => {
const CH = '<'.charCodeAt(0)
const pos = state.bMarks[startLine] + state.tShift[startLine]
@ -209,15 +213,13 @@ export const snippetPlugin = (md: MarkdownItAsync, srcDir: string) => {
const regions = findRegions(lines, region)
if (regions.length > 0) {
content = dedent(
regions
.flatMap((r) =>
lines
.slice(r.start, r.end)
.filter((l) => !(r.re.start.test(l) || r.re.end.test(l)))
)
.join('\n')
)
content = regions
.flatMap((r) =>
lines
.slice(r.start, r.end)
.filter((l) => !(r.re.start.test(l) || r.re.end.test(l)))
)
.join('\n')
} else {
token.content = `No region #${region} found in path: ${src}`
token.info = ''
@ -225,7 +227,19 @@ export const snippetPlugin = (md: MarkdownItAsync, srcDir: string) => {
}
}
token.content = content
if (stripMarkersFromSnippets) {
content = content
.split('\n')
.filter((l) => {
for (const m of markers) {
if (m.start.test(l) || m.end.test(l)) return false
}
return true
})
.join('\n')
}
token.content = dedent(content)
return fence(...args)
}

Loading…
Cancel
Save