-
-
Notifications
You must be signed in to change notification settings - Fork 375
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(rehype): support inline codes (#751)
Co-authored-by: Anthony Fu <github@antfu.me>
- Loading branch information
Showing
8 changed files
with
310 additions
and
134 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import type { Element, Root } from 'hast' | ||
import { toString } from 'hast-util-to-string' | ||
import type { RehypeShikiCoreOptions } from './types' | ||
|
||
interface InlineCodeProcessorContext { | ||
node: Element | ||
getLanguage: (lang?: string) => string | undefined | ||
highlight: ( | ||
lang: string, | ||
code: string, | ||
metaString?: string, | ||
meta?: Record<string, unknown> | ||
) => Root | undefined | ||
} | ||
|
||
type InlineCodeProcessor = (context: InlineCodeProcessorContext) => Root | undefined | ||
|
||
type Truthy<T> = T extends false | '' | 0 | null | undefined ? never : T | ||
|
||
export const InlineCodeProcessors: Record<Truthy<RehypeShikiCoreOptions['inline']>, InlineCodeProcessor> = { | ||
'tailing-curly-colon': ({ node, getLanguage, highlight }) => { | ||
const raw = toString(node) | ||
const match = raw.match(/(.+)\{:([\w-]+)\}$/) | ||
if (!match) | ||
return | ||
const lang = getLanguage(match[2]) | ||
if (!lang) | ||
return | ||
|
||
const code = match[1] ?? raw | ||
const fragment = highlight(lang, code) | ||
if (!fragment) | ||
return | ||
|
||
const head = fragment.children[0] | ||
if (head.type === 'element' && head.tagName === 'pre') { | ||
head.tagName = 'span' | ||
} | ||
|
||
return fragment | ||
}, | ||
} |
Oops, something went wrong.