Skip to content

Commit

Permalink
feat: support specifying language while importing code snippets
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Jun 28, 2022
1 parent b2c3efc commit 7bfb463
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 20 deletions.
25 changes: 10 additions & 15 deletions docs/guide/markdown.md
Expand Up @@ -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.
:::
Expand All @@ -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

Expand Down
11 changes: 6 additions & 5 deletions src/node/markdown/plugins/snippet.ts
Expand Up @@ -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
Expand Down

0 comments on commit 7bfb463

Please sign in to comment.