feat: support specifying language while importing code snippets

pull/875/head
Divyansh Singh 3 years ago
parent b2c3efc1c8
commit 7bfb463c37

@ -346,20 +346,12 @@ It also supports [line highlighting](#line-highlighting-in-code-blocks):
**Code file**
<!--lint disable strong-marker-->
<<< @/snippets/snippet.js
<!--lint enable strong-marker-->
**Output**
<!--lint disable strong-marker-->
<<< @/snippets/snippet.js{2}
<!--lint enable strong-marker-->
::: 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**
<!--lint disable strong-marker-->
<<< @/snippets/snippet-with-region.js
<!--lint enable strong-marker-->
**Output**
<!--lint disable strong-marker-->
<<< @/snippets/snippet-with-region.js#snippet{1}
<!--lint enable strong-marker-->
You can also specify the language inside the braces (`{}`) like this:
```md
<<< @/snippets/snippet.cs{c#}
<!-- with line highlighting: -->
<<< @/snippets/snippet.cs{1,2,4-6 c#}
```
This is helpful if source language cannot be inferred from your file extension.
## Advanced Configuration

@ -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

Loading…
Cancel
Save