Skip to content

Commit 02a7441

Browse files
authored
Use first word only from info string to match language in code block highlighting (#1354)
1 parent b755793 commit 02a7441

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

.changeset/mighty-apples-tan.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@keystatic/core': patch
3+
---
4+
5+
Improve syntax highlighting in the `fields.mdx`/`fields.markdoc` editor to only use the first word in the info string to match the language. This is primarily for `fields.mdx` to allow additional information in the info string beyond the editor. In `fields.markdoc` additional content after the first word will be stripped since Markdoc expresses additional information using Markdoc annotations which Keystatic already exposes UI for if `options.codeBlock.schema` is configured.

packages/keystatic/src/form/fields/markdoc/editor/code-block-highlighting.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,21 @@ function getDecorationsForIndividualNode(node: Node): InlineDecorationSpec[] {
1717
if (!node.type.spec.code || !node.childCount) return emptyDecorations;
1818
const text = node.content.child(0).text;
1919
if (!text) return emptyDecorations;
20-
const lang = node.attrs.language;
21-
if (
22-
typeof lang !== 'string' ||
23-
!Object.prototype.hasOwnProperty.call(Prism.languages, node.attrs.language)
24-
) {
20+
let lang = node.attrs.language;
21+
if (typeof lang !== 'string') return emptyDecorations;
22+
lang = lang.trim();
23+
const spaceIndex = lang.indexOf(' ');
24+
if (spaceIndex !== -1) {
25+
lang = lang.slice(0, spaceIndex);
26+
}
27+
lang = lang.toLowerCase();
28+
if (!Object.prototype.hasOwnProperty.call(Prism.languages, lang)) {
2529
return emptyDecorations;
2630
}
31+
const prismLang = Prism.languages[lang];
32+
if (typeof prismLang !== 'object') return emptyDecorations;
2733
const decorations: InlineDecorationSpec[] = [];
28-
const tokens = Prism.tokenize(text, Prism.languages[node.attrs.language]);
34+
const tokens = Prism.tokenize(text, prismLang);
2935
function consumeTokens(start: number, tokens: (string | Prism.Token)[]) {
3036
for (const token of tokens) {
3137
const length = getPrismTokenLength(token);

0 commit comments

Comments
 (0)