Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): highlight code blocks in their declared language

Elian Doran9db45e20b39b
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 698de35520..7728064462 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,8 +39,10 @@ class="image">
<td>
<ul>
<li>Table of contents.</li>
- <li>Syntax highlight of code blocks. The language is detected automatically,
- among the ones enabled in <a class="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a> → <em>Code Notes</em>.</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>;
+ 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
notes are also shared).</li>
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index 1c1807b858..6156a203b0 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. The language is detected automatically, among the ones enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → <em>Code Notes</em>.</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></ul></td>
+ <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></ul></td>
<td><ul><li>Inline Mermaid diagrams are not rendered.</li></ul></td>
</tr>
<tr>
diff --git a/packages/highlightjs/src/index.ts b/packages/highlightjs/src/index.ts
index 689b0df808..4d4e038c1f 100644
--- a/packages/highlightjs/src/index.ts
+++ b/packages/highlightjs/src/index.ts
@@ -81,4 +81,4 @@ export async function loadTheme(theme: "none" | Theme) {
highlightingThemeEl.textContent = normalizeThemeCss(themeCss);
}
-export const { highlightAuto } = hljs;
+export const { getLanguage, highlightAuto } = hljs;
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index da3e972ac9..44fc053ef0 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -282,6 +282,43 @@ describe("content_renderer", () => {
`);
});
+ it("highlights a code block in the language it declares", async () => {
+ await ensureShareHighlighting();
+ const xml = "&lt;t t-name=&quot;x&quot;&gt;&lt;/t&gt;";
+ // text-x-cobol is not enabled by default, so it is never registered.
+ const languages = [ "text-x-python", "text-plain", "text-x-cobol", "text-x-trilium-auto" ];
+ const note = buildShareNote({
+ content: languages.map((language) => `<pre><code class="language-${language}">${xml}</code></pre>`).join("")
+ });
+
+ const result = getContent(note);
+ if (typeof result.content !== "string") throw new Error("expected string content");
+ const [ python, plain, cobol, auto ] = parse(result.content, { blockTextElements: {} }).querySelectorAll("code");
+ expect(python.classList.contains("hljs")).toBe(true);
+ expect(python.innerHTML).toContain("hljs-string");
+ expect(python.innerHTML).not.toContain("hljs-tag");
+ expect(plain.innerHTML).toBe(xml);
+ expect(cobol.innerHTML).toBe(xml);
+ expect(auto.innerHTML).toContain("hljs-tag");
+ });
+
+ it("highlights an included code note in its own language", async () => {
+ await ensureShareHighlighting();
+ buildShareNotes([
+ { id: "pycode", type: "code", mime: "text/x-python", content: `<t t-name="x"></t>` }
+ ]);
+ const note = buildShareNote({
+ content: `<section class="include-note" data-note-id="pycode" data-box-size="medium">&nbsp;</section>`
+ });
+
+ const result = getContent(note);
+ if (typeof result.content !== "string") throw new Error("expected string content");
+ const code = parse(result.content, { blockTextElements: {} }).querySelector("code");
+ expect(code?.classList.contains("language-text-x-python")).toBe(true);
+ expect(code?.innerHTML).toContain("hljs-string");
+ expect(code?.innerHTML).not.toContain("hljs-tag");
+ });
+
describe("Reference links", () => {
it("handles attachment link", () => {
const content = trimIndentation`\
diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.ts
index bd60470be9..374bd02d5c 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -1,7 +1,7 @@
-import { extractYouTubeVideoId, isHttpUrl, type MimeType, MIME_TYPES_DICT, safeLinkPreviewHref, safeLinkPreviewImageSrc } from "@triliumnext/commons";
+import { extractYouTubeVideoId, isHttpUrl, MIME_TYPE_AUTO, type MimeType, MIME_TYPES_DICT, normalizeMimeTypeForCKEditor, safeLinkPreviewHref, safeLinkPreviewImageSrc } from "@triliumnext/commons";
import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";
import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";
-import { ensureMimeTypes, highlightAuto } from "@triliumnext/highlightjs";
+import { ensureMimeTypes, getLanguage, highlight, highlightAuto } from "@triliumnext/highlightjs";
import ejs from "ejs";
import escapeHtml from "escape-html";
import { t } from "i18next";
@@ -45,6 +45,8 @@ const HIGHLIGHT_MAX_LINE_COUNT = 500;
*/
const HIGHLIGHT_MAX_CHAR_COUNT = 50_000;
+const PLAIN_TEXT_LANGUAGE = normalizeMimeTypeForCKEditor("text/plain");
+
/**
* The base a web view's rooted source is resolved against, to tell a path that stays on this site
* from one that only looks rooted at it. `.invalid` is reserved and resolves nowhere, so a source
@@ -339,7 +341,7 @@ export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}
} else if (note.type === "code" && note.mime === "text/x-markdown") {
renderMarkdown(result, note);
} else if (note.type === "code") {
- renderCode(result);
+ renderCode(result, note.mime);
} else if (note.type === "mermaid") {
renderMermaid(result, note);
} else if (["image", "canvas", "mindMap"].includes(note.type)) {
@@ -547,15 +549,7 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt
continue;
}
- // codeEl.text recursively traverses the node's subtree, so read it once.
- const codeText = codeEl.text;
- if (!shouldSyntaxHighlight(codeText)) {
- continue;
- }
-
- const highlightResult = highlightAuto(codeText);
- codeEl.innerHTML = highlightResult.value;
- codeEl.classList.add("hljs");
+ highlightCodeBlock(codeEl);
}
result.content = document.innerHTML ?? "";
@@ -664,19 +658,11 @@ function renderMarkdown(result: Result, note: SNote | BNote) {
const document = parse(html, parseOpts);
for (const codeEl of document.querySelectorAll("pre code")) {
if (codeEl.classList.contains("language-mermaid")
- || codeEl.classList.contains("language-text-x-trilium-auto")) {
+ || codeEl.classList.contains(`language-${MIME_TYPE_AUTO}`)) {
continue;
}
- // codeEl.text recursively traverses the node's subtree, so read it once.
- const codeText = codeEl.text;
- if (!shouldSyntaxHighlight(codeText)) {
- continue;
- }
-
- const highlightResult = highlightAuto(codeText);
- codeEl.innerHTML = highlightResult.value;
- codeEl.classList.add("hljs");
+ highlightCodeBlock(codeEl);
}
result.content = document.innerHTML;
@@ -703,6 +689,33 @@ export function shouldSyntaxHighlight(code: string) {
return true;
}
+/**
+ * Highlights a `<pre><code>` block in place, in the language its `language-*` class names. A block
+ * without one, or set to auto-detect, goes through `highlightAuto`. Plain text and a language that
+ * {@link ensureShareHighlighting} did not register stay unhighlighted.
+ */
+function highlightCodeBlock(codeEl: HTMLElement) {
+ const language = [ ...codeEl.classList.values() ]
+ .find((className) => className.startsWith("language-"))
+ ?.slice("language-".length) ?? MIME_TYPE_AUTO;
+ const isAuto = language === MIME_TYPE_AUTO;
+ if (language === PLAIN_TEXT_LANGUAGE || (!isAuto && !getLanguage(language))) {
+ return;
+ }
+
+ // codeEl.text recursively traverses the node's subtree, so read it once.
+ const codeText = codeEl.text;
+ if (!shouldSyntaxHighlight(codeText)) {
+ return;
+ }
+
+ const highlightResult = isAuto ? highlightAuto(codeText) : highlight(codeText, { language });
+ if (highlightResult) {
+ codeEl.innerHTML = highlightResult.value;
+ codeEl.classList.add("hljs");
+ }
+}
+
let registeredMimeTypesOption: string | null = null;
let pendingRegistration: Promise<void> | null = null;
@@ -746,7 +759,7 @@ export function getMimeTypesForOption(optionValue: string | null): MimeType[] {
/**
* Renders a code note.
*/
-export function renderCode(result: Result) {
+export function renderCode(result: Result, mime?: string) {
if (typeof result.content !== "string" || !result.content?.trim()) {
result.isEmpty = true;
} else {
@@ -754,9 +767,10 @@ export function renderCode(result: Result) {
// When such a code note is included into a shared text note, renderText re-parses the
// resulting HTML; with unescaped angle brackets (e.g. generics, comparisons, JSX) a large
// code note would explode into a pathological node-html-parser tree and hang the event
- // loop (#9717). The <code> wrapper additionally lets renderText apply syntax highlighting,
- // bounded by shouldSyntaxHighlight().
- result.content = `<pre><code>${escapeHtml(result.content)}</code></pre>`;
+ // loop (#9717). The <code> wrapper and its `language-*` class additionally let renderText
+ // apply syntax highlighting, bounded by shouldSyntaxHighlight().
+ const languageClass = mime ? ` class="language-${escapeHtml(normalizeMimeTypeForCKEditor(mime))}"` : "";
+ result.content = `<pre><code${languageClass}>${escapeHtml(result.content)}</code></pre>`;
}
}