Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): color code blocks with VS Code themes in light and dark

Elian Doranbff2bf6c23f4
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
index c08cde3f82..36a731b1d1 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
@@ -39,9 +39,10 @@ class="image">
<td>
<ul>
<li>Table of contents.</li>
- <li>Syntax highlight of code blocks, in the language selected for each block.
- For “Auto-detected” blocks, the language is guessed among the ones enabled
- in <a class="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a> → <em>Code Notes</em>;
+ <li>Syntax highlight of code blocks, in the language selected for each block
+ and in the colors of the VS Code light or dark theme, following the page's
+ mode. For “Auto-detected” blocks, the language is guessed among the ones
+ enabled in <a class="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a> → <em>Code Notes</em>;
a language not enabled there is not highlighted.</li>
<li>Rendering for math equations.</li>
<li><a href="#root/_help_nBAXQFj20hS1">Including notes</a> (only if the included
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.html
index 4b18355d51..f464d9ac63 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.html
@@ -71,7 +71,9 @@
<p>In order to configure this new feature, a section has been added in&nbsp;<a
class="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a>&nbsp;→ <em>Appearance</em> to
control the syntax highlighting. There the color scheme can be chosen,
- from a builtin selection of themes from Highlight.js.</p>
+ from a builtin selection of themes from Highlight.js. <em>VS Code (Light)</em> and <em>VS Code (Dark)</em> use
+ the same colors as the default themes of <a class="reference-link" href="#root/_help_6f9hih2hXXZk">Code</a> notes,
+ so a code block and a code note color the same code alike.</p>
<ul>
<li>It is possible to disable the syntax highlighting for all the notes by
selecting “No syntax highlighting” in the “Color scheme” option.</li>
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index 32cda0bc43..45a6ea926f 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
@@ -32,7 +32,7 @@ Trilium allows you to share selected notes as **publicly accessible** read-only
<tbody>
<tr>
<th><a class="reference-link" href="../Note%20Types/Text.md">Text</a></th>
- <td><ul><li>Table of contents.</li><li>Syntax highlight of code blocks, in the language selected for each block. For “Auto-detected” blocks, the language is guessed among the ones enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → <em>Code Notes</em>; a language not enabled there is not highlighted.</li><li>Rendering for math equations.</li><li><a href="../Note%20Types/Text/Include%20Note.md">Including notes</a> (only if the included notes are also shared).</li><li>Mermaid diagrams in code blocks, drawn in the page's light or dark mode and redrawn when the visitor switches it.</li></ul></td>
+ <td><ul><li>Table of contents.</li><li>Syntax highlight of code blocks, in the language selected for each block and in the colors of the VS Code light or dark theme, following the page's mode. For “Auto-detected” blocks, the language is guessed among the ones enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → <em>Code Notes</em>; a language not enabled there is not highlighted.</li><li>Rendering for math equations.</li><li><a href="../Note%20Types/Text/Include%20Note.md">Including notes</a> (only if the included notes are also shared).</li><li>Mermaid diagrams in code blocks, drawn in the page's light or dark mode and redrawn when the visitor switches it.</li></ul></td>
<td>&nbsp;</td>
</tr>
<tr>
diff --git a/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md b/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md
index 9a25c6f8a2..c12402a4e3 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Developer-specific formatting/Code blocks.md
@@ -38,7 +38,7 @@ Interaction:
Note that when editing a text note, syntax highlighting is automatically disabled if the code block is too big (somewhere around 500 lines). This value is currently not configurable. For <a class="reference-link" href="../../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md">Read-Only Notes</a>, this limitation is not applied.
-In order to configure this new feature, a section has been added in <a class="reference-link" href="../../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Appearance_ to control the syntax highlighting. There the color scheme can be chosen, from a builtin selection of themes from Highlight.js.
+In order to configure this new feature, a section has been added in <a class="reference-link" href="../../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Appearance_ to control the syntax highlighting. There the color scheme can be chosen, from a builtin selection of themes from Highlight.js. _VS Code (Light)_ and _VS Code (Dark)_ use the same colors as the default themes of <a class="reference-link" href="../../Code.md">Code</a> notes, so a code block and a code note color the same code alike.
* It is possible to disable the syntax highlighting for all the notes by selecting “No syntax highlighting” in the “Color scheme” option.
* Word wrapping is disabled by default, but can be configured from the same section.
diff --git a/packages/highlightjs/src/themes.ts b/packages/highlightjs/src/themes.ts
index 88cb703aa3..a36b17dfb5 100644
--- a/packages/highlightjs/src/themes.ts
+++ b/packages/highlightjs/src/themes.ts
@@ -1,3 +1,5 @@
+import { buildVsCodeThemeCss, VS_CODE_DARK, VS_CODE_LIGHT } from "./vs_code_theme.js";
+
export type ThemeVariant = "light" | "dark";
export interface Theme {
@@ -334,6 +336,14 @@ const themeDefinitions: Record<string, Theme> = {
name: "Visual Studio (Light)",
load: () => import("highlight.js/styles/vs.css?raw")
},
+ "vs-code-dark": {
+ name: "VS Code (Dark)",
+ load: async () => ({ default: buildVsCodeThemeCss(VS_CODE_DARK) })
+ },
+ "vs-code-light": {
+ name: "VS Code (Light)",
+ load: async () => ({ default: buildVsCodeThemeCss(VS_CODE_LIGHT) })
+ },
"vs2015": {
name: "Visual Studio 2015 (Dark)",
load: () => import("highlight.js/styles/vs2015.css?raw")
diff --git a/packages/highlightjs/src/vs_code_theme.spec.ts b/packages/highlightjs/src/vs_code_theme.spec.ts
new file mode 100644
index 0000000000..5d112ab04b
--- /dev/null
+++ b/packages/highlightjs/src/vs_code_theme.spec.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from "vitest";
+
+import { normalizeThemeCss } from "./index.js";
+import themeDefinitions, { getThemeVariant } from "./themes.js";
+import { buildVsCodeThemeCss, VS_CODE_DARK, VS_CODE_LIGHT } from "./vs_code_theme.js";
+
+describe("buildVsCodeThemeCss", () => {
+ it("colors each token kind from the palette, with the block background", () => {
+ const css = buildVsCodeThemeCss(VS_CODE_DARK);
+
+ expect(css).toMatch(/^\.hljs \{ color: #d4d4d4; background: #1e1e1e; \}/);
+ expect(css).toContain(".hljs-keyword, .hljs-literal, .hljs-variable.language_, "
+ + ".hljs-template-tag, .hljs-selector-tag, .hljs-name { color: #569cd6; }");
+ expect(css).toContain(".hljs-title.function_ { color: #dcdcaa; }");
+ expect(css).toContain(".hljs-comment, .hljs-quote { color: #6a9955; font-style: italic; }");
+ // The app widens the block selector so it applies inside the editor.
+ expect(normalizeThemeCss(css)).toMatch(/^\.hljs, \.ck-content pre\.hljs \{/);
+ });
+
+ it("scopes every selector, the block layout included", () => {
+ const css = buildVsCodeThemeCss(VS_CODE_LIGHT, ":where(html.theme-light)");
+
+ expect(css).toMatch(
+ /^:where\(html\.theme-light\) \.hljs \{ color: #383a42; background: #ffffff; \}/);
+ expect(css).toContain(
+ ":where(html.theme-light) .hljs-string, :where(html.theme-light) .hljs-addition");
+ expect(css).toContain(":where(html.theme-light) pre code.hljs { display: block;");
+ for (const selector of css.match(/[^{}]+(?=\{)/g) ?? []) {
+ for (const part of selector.split(",")) {
+ expect(part.trim()).toMatch(/^:where\(html\.theme-light\) /);
+ }
+ }
+ });
+});
+
+describe("VS Code themes", () => {
+ it("are registered as a light and a dark theme", () => {
+ expect(getThemeVariant(themeDefinitions["vs-code-light"])).toBe("light");
+ expect(getThemeVariant(themeDefinitions["vs-code-dark"])).toBe("dark");
+ });
+});
diff --git a/packages/highlightjs/src/vs_code_theme.ts b/packages/highlightjs/src/vs_code_theme.ts
new file mode 100644
index 0000000000..b33c288b31
--- /dev/null
+++ b/packages/highlightjs/src/vs_code_theme.ts
@@ -0,0 +1,113 @@
+/**
+ * Colors of a VS Code highlight.js theme, by the role a token plays. The values are those of the
+ * `@fsegurai/codemirror-theme-vscode-*` themes code notes use, so a code block in a text note and a
+ * code note color the same token alike.
+ */
+export interface VsCodePalette {
+ foreground: string;
+ background: string;
+ keyword: string;
+ controlKeyword: string;
+ type: string;
+ function: string;
+ variable: string;
+ number: string;
+ string: string;
+ regexp: string;
+ comment: string;
+ meta: string;
+ selector: string;
+ emphasis: string;
+ link: string;
+ deleted: string;
+}
+
+export const VS_CODE_LIGHT: VsCodePalette = {
+ foreground: "#383a42",
+ background: "#ffffff",
+ keyword: "#0064ff",
+ controlKeyword: "#af00db",
+ type: "#267f99",
+ function: "#795e26",
+ variable: "#0070c1",
+ number: "#098658",
+ string: "#a31515",
+ regexp: "#af00db",
+ comment: "#008000",
+ meta: "#6b6b6b",
+ selector: "#795e26",
+ emphasis: "#0070c1",
+ link: "#006ab1",
+ deleted: "#e51400"
+};
+
+export const VS_CODE_DARK: VsCodePalette = {
+ foreground: "#d4d4d4",
+ background: "#1e1e1e",
+ keyword: "#569cd6",
+ controlKeyword: "#c586c0",
+ type: "#4ec9b0",
+ function: "#dcdcaa",
+ variable: "#9cdcfe",
+ number: "#b5cea8",
+ string: "#ce9178",
+ regexp: "#d16969",
+ comment: "#6a9955",
+ meta: "#838383",
+ selector: "#d7ba7d",
+ emphasis: "#4ec9b0",
+ link: "#3794ff",
+ deleted: "#f44747"
+};
+
+/**
+ * Writes the highlight.js stylesheet for a VS Code palette.
+ *
+ * @param scope a selector every rule is nested under, such as `:where(html.theme-dark)`.
+ */
+export function buildVsCodeThemeCss(palette: VsCodePalette, scope?: string) {
+ const rules: [ string[], string ][] = [
+ [ [ ".hljs" ], `color: ${palette.foreground}; background: ${palette.background};` ],
+ [ [
+ ".hljs-keyword", ".hljs-literal", ".hljs-variable.language_", ".hljs-template-tag",
+ ".hljs-selector-tag", ".hljs-name"
+ ], `color: ${palette.keyword};` ],
+ [ [ ".hljs-meta .hljs-keyword" ], `color: ${palette.controlKeyword};` ],
+ [ [
+ ".hljs-built_in", ".hljs-type", ".hljs-title.class_", ".hljs-title.class_.inherited__"
+ ], `color: ${palette.type};` ],
+ [ [ ".hljs-title", ".hljs-title.function_" ], `color: ${palette.function};` ],
+ [ [
+ ".hljs-variable", ".hljs-params", ".hljs-property", ".hljs-attr", ".hljs-attribute",
+ ".hljs-template-variable", ".hljs-variable.constant_"
+ ], `color: ${palette.variable};` ],
+ [ [ ".hljs-number", ".hljs-symbol" ], `color: ${palette.number};` ],
+ [ [
+ ".hljs-string", ".hljs-addition", ".hljs-char.escape_", ".hljs-meta .hljs-string",
+ ".hljs-code"
+ ], `color: ${palette.string};` ],
+ [ [ ".hljs-regexp" ], `color: ${palette.regexp};` ],
+ [ [ ".hljs-comment", ".hljs-quote" ], `color: ${palette.comment}; font-style: italic;` ],
+ [ [ ".hljs-doctag" ], `color: ${palette.comment}; font-weight: bold;` ],
+ [ [ ".hljs-meta" ], `color: ${palette.meta};` ],
+ [ [
+ ".hljs-selector-id", ".hljs-selector-class", ".hljs-selector-attr",
+ ".hljs-selector-pseudo"
+ ], `color: ${palette.selector};` ],
+ [ [ ".hljs-section", ".hljs-bullet" ], `color: ${palette.keyword}; font-weight: bold;` ],
+ [ [ ".hljs-strong" ], `color: ${palette.keyword}; font-weight: bold;` ],
+ [ [ ".hljs-emphasis" ], `color: ${palette.emphasis}; font-style: italic;` ],
+ [ [ ".hljs-link" ], `color: ${palette.link}; text-decoration: underline;` ],
+ [ [ ".hljs-deletion" ], `color: ${palette.deleted};` ],
+ // The block layout every highlight.js theme carries.
+ [ [ "pre code.hljs" ], "display: block; overflow-x: auto; padding: 1em;" ],
+ [ [ "code.hljs" ], "padding: 3px 5px;" ]
+ ];
+
+ return rules
+ .map(([ selectors, declarations ]) => {
+ const scoped = scope ? selectors.map((selector) => `${scope} ${selector}`) : selectors;
+ return `${scoped.join(", ")} { ${declarations} }`;
+ })
+ .join("\n");
+}
diff --git a/packages/share-theme/package.json b/packages/share-theme/package.json
index 4c9629c803..7980e9ad4c 100644
--- a/packages/share-theme/package.json
+++ b/packages/share-theme/package.json
@@ -4,9 +4,9 @@
"description": "Default theme for shared notes and static HTML exports",
"type": "module",
"scripts": {
- "dev": "esrun scripts/build.ts -- --watch",
- "build": "esrun scripts/build.ts",
- "dist": "esrun scripts/build.ts -- --minify",
+ "dev": "tsx scripts/build.ts --watch",
+ "build": "tsx scripts/build.ts",
+ "dist": "tsx scripts/build.ts --minify",
"test": "vitest run"
},
"exports": {
@@ -24,11 +24,10 @@
"katex": "0.19.0"
},
"devDependencies": {
- "@digitak/esrun": "3.2.26",
"@triliumnext/ckeditor5": "workspace:*",
+ "@triliumnext/highlightjs": "workspace:*",
"esbuild": "0.28.2",
"happy-dom": "20.14.5",
- "highlight.js": "11.12.0",
"sass": "1.105.1",
"typescript": "6.0.3",
"vitest": "5.0.3"
diff --git a/packages/share-theme/scripts/build.ts b/packages/share-theme/scripts/build.ts
index 3a553005f5..6b8fb81e73 100644
--- a/packages/share-theme/scripts/build.ts
+++ b/packages/share-theme/scripts/build.ts
@@ -4,6 +4,9 @@ import * as esbuild from "esbuild";
import { rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { pathToFileURL } from "node:url";
+import {
+ buildVsCodeThemeCss, VS_CODE_DARK, VS_CODE_LIGHT
+} from "@triliumnext/highlightjs/src/vs_code_theme.js";
import * as sass from "sass";
const packageJson = process.env.npm_package_json;
@@ -37,6 +40,26 @@ const sassPlugin: esbuild.Plugin = {
}
};
+// Serves `virtual:code-themes.css`: the VS Code highlighting themes code notes also use, one per
+// share theme mode. `:where()` keeps the block rules as weak as a stock highlight.js theme's, so the
+// share theme's own `.ck-content code` colors still win inside text notes.
+const codeThemesPlugin: esbuild.Plugin = {
+ name: "code-themes",
+ setup(build) {
+ build.onResolve({ filter: /^virtual:code-themes\.css$/ }, (args) => ({
+ path: args.path,
+ namespace: "code-themes"
+ }));
+ build.onLoad({ filter: /.*/, namespace: "code-themes" }, () => ({
+ contents: [
+ buildVsCodeThemeCss(VS_CODE_LIGHT, ":where(html.theme-light)"),
+ buildVsCodeThemeCss(VS_CODE_DARK, ":where(html.theme-dark)")
+ ].join("\n"),
+ loader: "css"
+ }));
+ }
+};
+
const outDir = path.join(rootDir, "dist");
async function runBuild(watch: boolean) {
@@ -65,7 +88,7 @@ async function runBuild(watch: boolean) {
".html": "text",
".css": "css"
},
- plugins: [sassPlugin],
+ plugins: [ sassPlugin, codeThemesPlugin ],
logLevel: "info",
metafile: true,
minify: process.argv.includes("--minify")
diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.ts
index c6fd786dcc..f5f0674c7f 100644
--- a/packages/share-theme/src/index.ts
+++ b/packages/share-theme/src/index.ts
@@ -18,7 +18,7 @@ import setupLinkEmbeds from "./content/link_embed.js";
import setupMath from "./content/math.js";
import setupMermaid from "./content/mermaid.js";
import api from "./api.js";
-import "highlight.js/styles/default.css";
+import "virtual:code-themes.css";
import "@triliumnext/ckeditor5/src/theme/ck-content.css";
import "@triliumnext/ckeditor5/src/theme/tabs.css";
import "@triliumnext/ckeditor5/src/theme/multicolumn.css";
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8a0d1c3d5d..9e419fef9f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1361,21 +1361,18 @@ importers:
specifier: 0.19.0
version: 0.19.0
devDependencies:
- '@digitak/esrun':
- specifier: 3.2.26
- version: 3.2.26
'@triliumnext/ckeditor5':
specifier: workspace:*
version: link:../ckeditor5
+ '@triliumnext/highlightjs':
+ specifier: workspace:*
+ version: link:../highlightjs
esbuild:
specifier: 0.28.2
version: 0.28.2
happy-dom:
specifier: 20.14.5
version: 20.14.5
- highlight.js:
- specifier: 11.12.0
- version: 11.12.0
sass:
specifier: 1.105.1
version: 1.105.1
@@ -2242,14 +2239,6 @@ packages:
peerDependencies:
postcss-selector-parser: ^7.1.1
- '@digitak/[email protected]':
- resolution: {integrity: sha512-mL0bw7NhKVghp7mVsPwnAMhCn4NGAsk0KKFmAfnrYAZ/QCXR5xLXIYP82zLMjcsQag8DD6i1c+Yrm/57StYVzg==}
- engines: {node: '>=14.0'}
- hasBin: true
-
- '@digitak/[email protected]':
- resolution: {integrity: sha512-pqsnp2BUYlDoTXWG34HWgEJse/Eo1okRgNex8IG84wHrJp8h3SakeR5WhB4VxSA2+/D+frNYJ0ch3yXzsfNDoA==}
-
'@electron-forge/[email protected]':
resolution: {integrity: sha512-zbkmgt7vtL8OBY7YDwVizhCfAHJLpmQtA35iOKGWPpLWRZbGADVyIUZz3QZrbc2V81/BkrBerURIBXdd/fnyhQ==}
engines: {node: '>= 22.13.0'}
@@ -12596,14 +12585,6 @@ snapshots:
dependencies:
postcss-selector-parser: 7.1.6
- '@digitak/[email protected]':
- dependencies:
- '@digitak/grubber': 3.1.4
- chokidar: 3.6.0
- esbuild: 0.28.2
-
- '@digitak/[email protected]': {}
-
dependencies:
'@electron-forge/core': 8.0.1([email protected])