Skip to content

Commit

Permalink
feat(build): support relative path for code snippet (#1894)
Browse files Browse the repository at this point in the history
Co-authored-by: Divyansh Singh <40380293+brc-dd@users.noreply.github.com>
  • Loading branch information
CHOYSEN and brc-dd committed Jun 10, 2023
1 parent 80e734d commit 90478b3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
7 changes: 6 additions & 1 deletion docs/guide/markdown.md
Expand Up @@ -566,7 +566,12 @@ It also supports [line highlighting](#line-highlighting-in-code-blocks):
<<< @/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.
The value of `@` corresponds to the source root. By default it's the VitePress project root, unless `srcDir` is configured. Alternatively, you can also import from relative paths:

```md
<<< ../snippets/snippet.js
```

:::

You can also use a [VS Code region](https://code.visualstudio.com/docs/editor/codebasics#_folding) to only include the corresponding part of the code file. You can provide a custom region name after a `#` following the filepath:
Expand Down
14 changes: 9 additions & 5 deletions src/node/markdown/plugins/snippet.ts
Expand Up @@ -2,6 +2,7 @@ import fs from 'fs-extra'
import path from 'path'
import type MarkdownIt from 'markdown-it'
import type { RuleBlock } from 'markdown-it/lib/parser_block'
import type { MarkdownEnv } from '../env'

export function dedent(text: string): string {
const lines = text.split('\n')
Expand Down Expand Up @@ -107,15 +108,15 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => {
.trim()

const [
filename = '',
filepath = '',
extension = '',
region = '',
lines = '',
lang = '',
rawTitle = ''
] = (rawPathRegexp.exec(rawPath) || []).slice(1)

const title = rawTitle || filename.split('/').pop() || ''
const title = rawTitle || filepath.split('/').pop() || ''

state.line = startLine + 1

Expand All @@ -124,8 +125,12 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => {
title ? `[${title}]` : ''
}`

const resolvedPath = path.resolve(
path.dirname((state.env as MarkdownEnv).path),
filepath
)
// @ts-ignore
token.src = path.resolve(filename) + region
token.src = [resolvedPath, region.slice(1)]
token.markup = '```'
token.map = [startLine, startLine + 1]

Expand All @@ -138,8 +143,7 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => {
const [tokens, idx, , { loader }] = args
const token = tokens[idx]
// @ts-ignore
const tokenSrc = token.src
const [src, regionName] = tokenSrc ? tokenSrc.split('#') : ['']
const [src, regionName] = token.src ?? []

if (src) {
if (loader) {
Expand Down

0 comments on commit 90478b3

Please sign in to comment.