feat: support adding extra attributes to snippet imports (useful for twoslash) (#4100)

pull/4177/head
Thy 1 year ago committed by GitHub
parent 315c220049
commit e8f7dd16f6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -16,7 +16,7 @@ import type { MarkdownEnv } from '../../shared'
* captures: ['/path/to/file.extension', 'extension', '#region', '{meta}', '[title]'] * captures: ['/path/to/file.extension', 'extension', '#region', '{meta}', '[title]']
*/ */
export const rawPathRegexp = export const rawPathRegexp =
/^(.+?(?:(?:\.([a-z0-9]+))?))(?:(#[\w-]+))?(?: ?(?:{(\d+(?:[,-]\d+)*)? ?(\S+)?}))? ?(?:\[(.+)\])?$/ /^(.+?(?:(?:\.([a-z0-9]+))?))(?:(#[\w-]+))?(?: ?(?:{(\d+(?:[,-]\d+)*)? ?(\S+)? ?(\S+)?}))? ?(?:\[(.+)\])?$/
export function rawPathToToken(rawPath: string) { export function rawPathToToken(rawPath: string) {
const [ const [
@ -25,12 +25,13 @@ export function rawPathToToken(rawPath: string) {
region = '', region = '',
lines = '', lines = '',
lang = '', lang = '',
attrs = '',
rawTitle = '' rawTitle = ''
] = (rawPathRegexp.exec(rawPath) || []).slice(1) ] = (rawPathRegexp.exec(rawPath) || []).slice(1)
const title = rawTitle || filepath.split('/').pop() || '' const title = rawTitle || filepath.split('/').pop() || ''
return { filepath, extension, region, lines, lang, title } return { filepath, extension, region, lines, lang, attrs, title }
} }
export function dedent(text: string): string { export function dedent(text: string): string {
@ -126,7 +127,7 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => {
.replace(/^@/, srcDir) .replace(/^@/, srcDir)
.trim() .trim()
const { filepath, extension, region, lines, lang, title } = const { filepath, extension, region, lines, lang, attrs, title } =
rawPathToToken(rawPath) rawPathToToken(rawPath)
state.line = startLine + 1 state.line = startLine + 1
@ -134,7 +135,7 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => {
const token = state.push('fence', 'code', 0) const token = state.push('fence', 'code', 0)
token.info = `${lang || extension}${lines ? `{${lines}}` : ''}${ token.info = `${lang || extension}${lines ? `{${lines}}` : ''}${
title ? `[${title}]` : '' title ? `[${title}]` : ''
}` } ${attrs ?? ''}`
const { realPath, path: _path } = state.env as MarkdownEnv const { realPath, path: _path } = state.env as MarkdownEnv
const resolvedPath = path.resolve(path.dirname(realPath ?? _path), filepath) const resolvedPath = path.resolve(path.dirname(realPath ?? _path), filepath)

Loading…
Cancel
Save