Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/satteri-prism.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@astrojs/markdown-satteri': minor
'@astrojs/mdx': patch
---

Adds support for Prism syntax highlighting to the Sätteri Markdown and MDX processors. Setting `markdown.syntaxHighlight` to `'prism'` now highlights your code blocks with Prism.

```js
// astro.config.mjs
import { satteri } from '@astrojs/markdown-satteri';

export default defineConfig({
markdown: {
processor: satteri(),
syntaxHighlight: 'prism',
},
});
```
46 changes: 10 additions & 36 deletions packages/integrations/mdx/src/satteri/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { pathToFileURL } from 'node:url';
import type { MarkdownHeading } from '@astrojs/internal-helpers/markdown';
import { createShikiHighlighter } from '@astrojs/internal-helpers/shiki';
import type { SatteriResolvedOptions } from '@astrojs/markdown-satteri';
import {
satteriCollectImagesPlugin,
satteriCreateHighlightFn,
satteriHeadingIdsPlugin,
satteriShikiPlugin,
satteriHighlightPlugin,
} from '@astrojs/markdown-satteri';
import { createDefaultAstroMetadata } from 'astro/markdown';
import {
Expand Down Expand Up @@ -48,38 +48,12 @@ export function createMdxProcessor(
let highlightFn: HighlightFn | undefined;
let initPromise: Promise<void> | undefined;

function initShiki() {
const syntaxHighlight = mdxOptions.syntaxHighlight;
const syntaxHighlightType =
typeof syntaxHighlight === 'string'
? syntaxHighlight
: syntaxHighlight
? syntaxHighlight.type
: undefined;

if (syntaxHighlightType === 'prism') {
throw new Error(
'Prism syntax highlighting is not supported by the `satteri()` markdown processor. Use shiki instead, or switch to `markdown.processor: unified({...})`.',
);
}

if (syntaxHighlightType === 'shiki') {
const shikiConfig = mdxOptions.shikiConfig ?? {};
initPromise = createShikiHighlighter({
langs: shikiConfig.langs,
theme: shikiConfig.theme,
themes: shikiConfig.themes,
langAlias: shikiConfig.langAlias,
}).then((hl) => {
highlightFn = (code, lang, meta) =>
hl.codeToHtml(code, lang, {
meta,
wrap: shikiConfig.wrap,
defaultColor: shikiConfig.defaultColor,
transformers: shikiConfig.transformers,
});
});
}
function initHighlighter() {
initPromise = satteriCreateHighlightFn(mdxOptions.syntaxHighlight, mdxOptions.shikiConfig).then(
(fn) => {
highlightFn = fn;
},
);
}

return {
Expand All @@ -89,7 +63,7 @@ export function createMdxProcessor(
frontmatter: Record<string, any>,
): Promise<CompileMdxResult> {
if (!highlightFn && !initPromise) {
initShiki();
initHighlighter();
}
if (initPromise) await initPromise;

Expand Down Expand Up @@ -124,7 +98,7 @@ export function createMdxProcessor(
if (highlightFn) {
// `mdx: true` wraps the highlighted HTML in a JSX `<Fragment set:html>` node
// rather than a raw HTML node, since the Sätteri pipeline is compiling to JSX.
hastPlugins.push(satteriShikiPlugin(highlightFn, excludeLangs, { mdx: true }));
hastPlugins.push(satteriHighlightPlugin(highlightFn, excludeLangs, { mdx: true }));
}
if (satteriOptions.hastPlugins.length) {
hastPlugins.push(...satteriOptions.hastPlugins);
Expand Down
1 change: 1 addition & 0 deletions packages/markdown/satteri/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
},
"dependencies": {
"@astrojs/internal-helpers": "workspace:*",
"@astrojs/prism": "workspace:*",
"github-slugger": "^2.0.0",
"satteri": "^0.8.0"
},
Expand Down
5 changes: 4 additions & 1 deletion packages/markdown/satteri/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ export {
createCollectImagesPlugin as satteriCollectImagesPlugin,
createHeadingIdsPlugin as satteriHeadingIdsPlugin,
createImageMarkerPlugin as satteriImageMarkerPlugin,
createShikiPlugin as satteriShikiPlugin,
createHighlightPlugin as satteriHighlightPlugin,
/** @deprecated Renamed to `satteriHighlightPlugin` (it drives both Shiki and Prism). */
createHighlightPlugin as satteriShikiPlugin,
createHighlightFn as satteriCreateHighlightFn,
collectHastText as satteriCollectHastText,
makeFragmentNode as satteriMakeFragmentNode,
createSatteriMarkdownProcessor,
Expand Down
79 changes: 47 additions & 32 deletions packages/markdown/satteri/src/satteri-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,14 +177,14 @@ export function createImageMarkerPlugin(
};
}

export function createShikiPlugin(
export function createHighlightPlugin(
highlight: HighlightFn,
excludeLangs: string[] | undefined,
options?: { mdx?: boolean },
): HastPluginDefinition {
const wrapResult = options?.mdx ? makeFragmentNode : makeRawNode;
return {
name: 'shiki-highlight',
name: 'highlight',
element: {
filter: ['pre'],
async visit(node, ctx) {
Expand Down Expand Up @@ -217,6 +217,49 @@ export interface SatteriMarkdownProcessorOptions extends AstroMarkdownOptions {
features?: Features;
}

/**
* Build the highlighter for the Sätteri pipeline, or `undefined` when syntax
* highlighting is disabled. Shiki and Prism both resolve to a `HighlightFn`
* that turns a code block into a complete `<pre>` HTML string.
*/
export async function createHighlightFn(
syntaxHighlight: AstroMarkdownOptions['syntaxHighlight'],
shikiConfig: AstroMarkdownOptions['shikiConfig'] | undefined,
): Promise<HighlightFn | undefined> {
const syntaxHighlightType =
typeof syntaxHighlight === 'string'
? syntaxHighlight
: syntaxHighlight
? syntaxHighlight.type
: undefined;

if (syntaxHighlightType === 'shiki') {
const hl = await createShikiHighlighter({
langs: shikiConfig?.langs,
theme: shikiConfig?.theme,
themes: shikiConfig?.themes,
langAlias: shikiConfig?.langAlias,
});
return (code, lang, meta) =>
hl.codeToHtml(code, lang, {
meta,
wrap: shikiConfig?.wrap,
defaultColor: shikiConfig?.defaultColor,
transformers: shikiConfig?.transformers,
});
}

if (syntaxHighlightType === 'prism') {
const { runHighlighterWithAstro } = await import('@astrojs/prism/dist/highlighter');
return async (code, lang) => {
const { html, classLanguage } = await runHighlighterWithAstro(lang, code);
return `<pre class="${classLanguage}" data-language="${lang}"><code class="${classLanguage}">${html}</code></pre>`;
};
}

return undefined;
}

export async function createSatteriMarkdownProcessor(
opts?: SatteriMarkdownProcessorOptions,
): Promise<MarkdownRenderer> {
Expand All @@ -232,35 +275,7 @@ export async function createSatteriMarkdownProcessor(
features: userFeatures,
} = opts ?? {};

const syntaxHighlightType =
typeof syntaxHighlight === 'string'
? syntaxHighlight
: syntaxHighlight
? syntaxHighlight.type
: undefined;

if (syntaxHighlightType === 'prism') {
throw new Error(
'Prism syntax highlighting is not supported by the `satteri()` markdown processor. Use shiki instead, or switch to `markdown.processor: unified({...})`.',
);
}

let highlightFn: HighlightFn | undefined;
if (syntaxHighlightType === 'shiki') {
const hl = await createShikiHighlighter({
langs: shikiConfig.langs,
theme: shikiConfig.theme,
themes: shikiConfig.themes,
langAlias: shikiConfig.langAlias,
});
highlightFn = (code, lang, meta) =>
hl.codeToHtml(code, lang, {
meta,
wrap: shikiConfig.wrap,
defaultColor: shikiConfig.defaultColor,
transformers: shikiConfig.transformers,
});
}
const highlightFn = await createHighlightFn(syntaxHighlight, shikiConfig);

const syntaxHighlightExcludeLangs =
typeof syntaxHighlight === 'object' ? syntaxHighlight.excludeLangs : undefined;
Expand All @@ -279,7 +294,7 @@ export async function createSatteriMarkdownProcessor(

const hastPlugins: HastPluginDefinition[] = [];
if (highlightFn) {
hastPlugins.push(createShikiPlugin(highlightFn, syntaxHighlightExcludeLangs));
hastPlugins.push(createHighlightPlugin(highlightFn, syntaxHighlightExcludeLangs));
}
hastPlugins.push(...userHastPlugins);
hastPlugins.push(createImageMarkerPlugin(localImagePaths, remoteImagePaths));
Expand Down
20 changes: 15 additions & 5 deletions packages/markdown/satteri/test/highlight.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,20 @@ describe('satteri highlight', () => {
assert.ok(!code.includes('background-color:'));
});

it('rejects prism highlighting', async () => {
await assert.rejects(
createSatteriMarkdownProcessor({ syntaxHighlight: { type: 'prism' } }),
/Prism syntax highlighting is not supported/,
);
it('highlights using prism', async () => {
const processor = await createSatteriMarkdownProcessor({
syntaxHighlight: { type: 'prism' },
});
const { code } = await processor.render('```js\nconsole.log("Hello, world!");\n```');
assert.match(code, /<pre class="language-js" data-language="js">/);
assert.match(code, /class="token /);
});

it('supports prism excludeLangs', async () => {
const processor = await createSatteriMarkdownProcessor({
syntaxHighlight: { type: 'prism', excludeLangs: ['js'] },
});
const { code } = await processor.render('```js\nconsole.log("Hello, world!");\n```');
assert.ok(!code.includes('class="token '));
});
});
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading