Skip to content

Commit 9f88e1a

Browse files
committed
Apply background color and modifiers from syntax themes
Catpuccin themes (e.g. https://textmate-grammars-themes.netlify.app/?theme=catppuccin-mocha&grammar=rust) seem to use italics, so added support for them. Don't see any themes setting bgColor, but might as well.
1 parent 5368f5e commit 9f88e1a

File tree

2 files changed

+35
-12
lines changed

2 files changed

+35
-12
lines changed

src/highlightSyntaxInLine.ts

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,35 @@
11
import path from 'path';
22
import * as shiki from 'shiki';
33
import { FormattedString } from './formattedString';
4-
import { parseColorDefinition, ThemeColor } from './themes';
4+
import { ColorModifier, parseColorDefinition, ThemeColor } from './themes';
55
export type HighlightedText = [string, ThemeColor | null];
66

7+
function parseShikiColor(token: shiki.ThemedToken): ThemeColor {
8+
let modifiers: ColorModifier[] | undefined;
9+
if (
10+
token.fontStyle !== undefined &&
11+
token.fontStyle !== shiki.FontStyle.NotSet &&
12+
token.fontStyle !== shiki.FontStyle.None
13+
) {
14+
modifiers = [];
15+
if (token.fontStyle & shiki.FontStyle.Bold) {
16+
modifiers.push('bold');
17+
}
18+
if (token.fontStyle & shiki.FontStyle.Italic) {
19+
modifiers.push('italic');
20+
}
21+
if (token.fontStyle & shiki.FontStyle.Underline) {
22+
modifiers.push('underline');
23+
}
24+
}
25+
const themeColor = parseColorDefinition({
26+
color: token.color,
27+
backgroundColor: token.bgColor,
28+
modifiers,
29+
});
30+
return themeColor;
31+
}
32+
733
export async function highlightSyntaxInLine(
834
line: FormattedString,
935
fileName: string,
@@ -23,14 +49,11 @@ export async function highlightSyntaxInLine(
2349
theme,
2450
});
2551

26-
let index = 0;
27-
for (const { content, color } of tokens.flat()) {
28-
if (color) {
29-
const syntaxColor = parseColorDefinition({
30-
color: color,
31-
});
32-
line.addSpan(index, index + content.length, syntaxColor);
33-
index += content.length;
34-
}
52+
for (const token of tokens.flat()) {
53+
line.addSpan(
54+
token.offset,
55+
token.offset + token.content.length,
56+
parseShikiColor(token)
57+
);
3558
}
3659
}

src/themes.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ const THEMES_DIR = path.resolve(
1414
*/
1515
type Color = string;
1616

17-
type ColorModifier =
17+
export type ColorModifier =
1818
| 'reset'
1919
| 'bold'
2020
| 'dim'
@@ -25,7 +25,7 @@ type ColorModifier =
2525
| 'strikethrough'
2626
| 'visible';
2727

28-
type ColorDefinition = {
28+
export type ColorDefinition = {
2929
color?: Color;
3030
backgroundColor?: Color;
3131
modifiers?: ColorModifier[];

0 commit comments

Comments
 (0)