Skip to content
This repository has been archived by the owner on Feb 7, 2024. It is now read-only.

Commit

Permalink
feat(core): introduce tokens hook to transformers
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Jan 14, 2024
1 parent b7637bc commit 35e8da0
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 7 deletions.
3 changes: 3 additions & 0 deletions packages/shikiji-core/src/renderer-hast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ export function codeToHast(
throw new Error('[shikiji] Invalid options, either `theme` or `themes` must be provided')
}

for (const transformer of options.transformers || [])
tokens = transformer.tokens?.call(transformerContext, tokens) || tokens

return tokensToHast(
tokens,
{
Expand Down
2 changes: 1 addition & 1 deletion packages/shikiji-core/src/renderer-html-themes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function codeToTokensWithThemes(
internal: ShikiInternal,
code: string,
options: CodeToTokensWithThemesOptions,
) {
): ThemedTokenWithVariants[][] {
const themes = Object.entries(options.themes)
.filter(i => i[1])
.map(i => ({ color: i[0], theme: i[1]! }))
Expand Down
15 changes: 9 additions & 6 deletions packages/shikiji-core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,15 @@ export interface ShikijiTransformer {
* Name of the transformer
*/
name?: string
/**
* Transform the raw input code before passing to the highlighter.
*/
preprocess?(this: ShikijiTransformerContextCommon, code: string, options: CodeToHastOptions): string | void
/**
* Transform the full tokens list before converting to HAST.
* Return a new tokens list will replace the original one.
*/
tokens?(this: ShikijiTransformerContextCommon, tokens: ThemedToken[][]): ThemedToken[][] | void
/**
* Transform the entire generated HAST tree. Return a new Node will replace the original one.
*/
Expand All @@ -494,12 +503,6 @@ export interface ShikijiTransformer {
* Transform each token `<span>` element.
*/
token?(this: ShikijiTransformerContext, hast: Element, line: number, col: number, lineElement: Element): Element | void

/**
* Transform the raw input code before passing to the highlighter.
* This hook will only be called with `codeToHtml` or `codeToHast`.
*/
preprocess?(this: ShikijiTransformerContextCommon, code: string, options: CodeToHastOptions): string | void
/**
* Transform the generated HTML string before returning.
* This hook will only be called with `codeToHtml`.
Expand Down

0 comments on commit 35e8da0

Please sign in to comment.