diff --git a/docs/guide/markdown.md b/docs/guide/markdown.md index a3466deb..37f500f6 100644 --- a/docs/guide/markdown.md +++ b/docs/guide/markdown.md @@ -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: diff --git a/src/node/markdown/plugins/snippet.ts b/src/node/markdown/plugins/snippet.ts index 190fef83..480baf4a 100644 --- a/src/node/markdown/plugins/snippet.ts +++ b/src/node/markdown/plugins/snippet.ts @@ -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') @@ -107,7 +108,7 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => { .trim() const [ - filename = '', + filepath = '', extension = '', region = '', lines = '', @@ -115,7 +116,7 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => { rawTitle = '' ] = (rawPathRegexp.exec(rawPath) || []).slice(1) - const title = rawTitle || filename.split('/').pop() || '' + const title = rawTitle || filepath.split('/').pop() || '' state.line = startLine + 1 @@ -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] @@ -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) {