Skip to content

Commit

Permalink
Apply background color and modifiers from syntax themes
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
banga committed Jul 5, 2024
1 parent 5368f5e commit 9f88e1a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 12 deletions.
43 changes: 33 additions & 10 deletions src/highlightSyntaxInLine.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
import path from 'path';
import * as shiki from 'shiki';
import { FormattedString } from './formattedString';
import { parseColorDefinition, ThemeColor } from './themes';
import { ColorModifier, parseColorDefinition, ThemeColor } from './themes';
export type HighlightedText = [string, ThemeColor | null];

function parseShikiColor(token: shiki.ThemedToken): ThemeColor {
let modifiers: ColorModifier[] | undefined;
if (
token.fontStyle !== undefined &&
token.fontStyle !== shiki.FontStyle.NotSet &&
token.fontStyle !== shiki.FontStyle.None
) {
modifiers = [];
if (token.fontStyle & shiki.FontStyle.Bold) {
modifiers.push('bold');
}
if (token.fontStyle & shiki.FontStyle.Italic) {
modifiers.push('italic');
}
if (token.fontStyle & shiki.FontStyle.Underline) {
modifiers.push('underline');
}
}
const themeColor = parseColorDefinition({
color: token.color,
backgroundColor: token.bgColor,
modifiers,
});
return themeColor;
}

export async function highlightSyntaxInLine(
line: FormattedString,
fileName: string,
Expand All @@ -23,14 +49,11 @@ export async function highlightSyntaxInLine(
theme,
});

let index = 0;
for (const { content, color } of tokens.flat()) {
if (color) {
const syntaxColor = parseColorDefinition({
color: color,
});
line.addSpan(index, index + content.length, syntaxColor);
index += content.length;
}
for (const token of tokens.flat()) {
line.addSpan(
token.offset,
token.offset + token.content.length,
parseShikiColor(token)
);
}
}
4 changes: 2 additions & 2 deletions src/themes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const THEMES_DIR = path.resolve(
*/
type Color = string;

type ColorModifier =
export type ColorModifier =
| 'reset'
| 'bold'
| 'dim'
Expand All @@ -25,7 +25,7 @@ type ColorModifier =
| 'strikethrough'
| 'visible';

type ColorDefinition = {
export type ColorDefinition = {
color?: Color;
backgroundColor?: Color;
modifiers?: ColorModifier[];
Expand Down

0 comments on commit 9f88e1a

Please sign in to comment.