From 7bfb463c37f6dcdacce567d938de3eabf943949c Mon Sep 17 00:00:00 2001 From: Divyansh Singh <40380293+brc-dd@users.noreply.github.com> Date: Tue, 28 Jun 2022 21:28:38 +0530 Subject: [PATCH] feat: support specifying language while importing code snippets --- docs/guide/markdown.md | 25 ++++++++++--------------- src/node/markdown/plugins/snippet.ts | 11 ++++++----- 2 files changed, 16 insertions(+), 20 deletions(-) diff --git a/docs/guide/markdown.md b/docs/guide/markdown.md index ee844d2a..0b9626b9 100644 --- a/docs/guide/markdown.md +++ b/docs/guide/markdown.md @@ -346,20 +346,12 @@ It also supports [line highlighting](#line-highlighting-in-code-blocks): **Code file** - - <<< @/snippets/snippet.js - - **Output** - - <<< @/snippets/snippet.js{2} - - ::: tip The value of `@` corresponds to the source root. By default it's the VitePress project root, unless `srcDir` is configured. ::: @@ -374,19 +366,22 @@ You can also use a [VS Code region](https://code.visualstudio.com/docs/editor/co **Code file** - - <<< @/snippets/snippet-with-region.js - - **Output** - - <<< @/snippets/snippet-with-region.js#snippet{1} - +You can also specify the language inside the braces (`{}`) like this: + +```md +<<< @/snippets/snippet.cs{c#} + + +<<< @/snippets/snippet.cs{1,2,4-6 c#} +``` + +This is helpful if source language cannot be inferred from your file extension. ## Advanced Configuration diff --git a/src/node/markdown/plugins/snippet.ts b/src/node/markdown/plugins/snippet.ts index c8e52153..5410c338 100644 --- a/src/node/markdown/plugins/snippet.ts +++ b/src/node/markdown/plugins/snippet.ts @@ -104,25 +104,26 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => { /** * raw path format: "/path/to/file.extension#region {meta}" * where #region and {meta} are optional + * and meta can be like '1,2,4-6 lang', 'lang' or '1,2,4-6' * * captures: ['/path/to/file.extension', 'extension', '#region', '{meta}'] */ const rawPathRegexp = - /^(.+(?:\.([a-z]+)))(?:(#[\w-]+))?(?: ?({\d+(?:[,-]\d+)*}))?$/ + /^(.+(?:\.([a-z]+)))(?:(#[\w-]+))?(?: ?(?:{(\d+(?:[,-]\d+)*)? ?(\S+)?}))?$/ const rawPath = state.src .slice(start, end) .trim() .replace(/^@/, srcDir) .trim() - const [filename = '', extension = '', region = '', meta = ''] = ( - rawPathRegexp.exec(rawPath) || [] - ).slice(1) + + const [filename = '', extension = '', region = '', lines = '', lang = ''] = + (rawPathRegexp.exec(rawPath) || []).slice(1) state.line = startLine + 1 const token = state.push('fence', 'code', 0) - token.info = extension + meta + token.info = `${lang || extension}${lines ? `{${lines}}` : ''}` // @ts-ignore token.src = path.resolve(filename) + region