client: Respect user language selection for editor

This commit is contained in:
Elian Doran 2024-10-27 11:18:36 +02:00
parent e931df721d
commit c4bd4eb440
No known key found for this signature in database
2 changed files with 32 additions and 3 deletions

View File

@ -181,7 +181,25 @@ function getMimeTypes() {
return mimeTypes;
}
let mimeToHighlightJsMapping = null;
function getHighlightJsNameForMime(mimeType) {
if (!mimeToHighlightJsMapping) {
const mimeTypes = getMimeTypes();
mimeToHighlightJsMapping = {};
for (const mimeType of mimeTypes) {
// The mime stored by CKEditor is text-x-csrc instead of text/x-csrc so we keep this format for faster lookup.
const normalizedMime = mimeType.mime.replace(/\//g, "-");
mimeToHighlightJsMapping[normalizedMime] = mimeType.highlightJs;
}
}
console.log("Mappings ", mimeToHighlightJsMapping);
return mimeToHighlightJsMapping[mimeType];
}
export default {
getMimeTypes,
loadMimeTypes
loadMimeTypes,
getHighlightJsNameForMime
}

View File

@ -1,3 +1,5 @@
import mime_types from "../../../services/mime_types.js";
export function initSyntaxHighlighting(editor) {
console.log("Init syntax highlight");
initTextEditor(editor);
@ -156,7 +158,8 @@ function highlightCodeBlock(codeBlock, writer) {
// Don't highlight if plaintext (note this needs to remove the markers
// above first, in case this was a switch from non plaintext to
// plaintext)
if (codeBlock.getAttribute("language") == "text-plain") {
const mimeType = codeBlock.getAttribute("language");
if (mimeType == "text-plain") {
// XXX There's actually a plaintext language that could be used
// if you wanted the non-highlight formatting of
// highlight.js css applied, see
@ -165,6 +168,14 @@ function highlightCodeBlock(codeBlock, writer) {
return;
}
// Find the corresponding language for the given mimetype.
const highlightJsLanguage = mime_types.getHighlightJsNameForMime(mimeType);
if (!highlightJsLanguage) {
console.warn(`Unsupported highlight.js for mime type ${mimeType}.`);
return;
}
// Don't highlight if the code is too big, as the typing performance will be highly degraded.
if (codeBlock.childCount >= HIGHLIGHT_MAX_BLOCK_COUNT) {
return;
@ -216,7 +227,7 @@ function highlightCodeBlock(codeBlock, writer) {
// If that is done, it would also be interesting to have an
// auto-detect option. See language mime types at
// https://github.com/zadam/trilium/blob/dbd312c88db2b000ec0ce18c95bc8a27c0e621a1/src/public/app/widgets/type_widgets/editable_text.js#L104
let highlightRes = hljs.highlightAuto(text);
let highlightRes = hljs.highlight(text, { language: highlightJsLanguage });
dbg("text\n" + text);
dbg("html\n" + highlightRes.value);