Skip to content

Build your personal knowledge base with Trilium Notes

fix(editor): syntax highlighting not working in nested elements (closes #1609, closes #843)

Elian Doran8b7f16d49b30
diff --git a/src/public/app/types.d.ts b/src/public/app/types.d.ts
index 0228c37568..e8ea4ad75b 100644
--- a/src/public/app/types.d.ts
+++ b/src/public/app/types.d.ts
@@ -296,6 +296,7 @@ declare global {
}
interface CKNode {
+ _children: CKNode[];
name: string;
childCount: number;
isEmpty: boolean;
diff --git a/src/public/app/widgets/type_widgets/ckeditor/syntax_highlight.ts b/src/public/app/widgets/type_widgets/ckeditor/syntax_highlight.ts
index 7ad0424acf..42a36b2b2a 100644
--- a/src/public/app/widgets/type_widgets/ckeditor/syntax_highlight.ts
+++ b/src/public/app/widgets/type_widgets/ckeditor/syntax_highlight.ts
@@ -101,10 +101,30 @@ function initTextEditor(textEditor: TextEditor) {
const changes = document.differ.getChanges();
let dirtyCodeBlocks = new Set<CKNode>();
+ function lookForCodeBlocks(node: CKNode) {
+ for (const child of node._children) {
+ if (child.is("element", "paragraph")) {
+ continue;
+ }
+
+ if (child.is("element", "codeBlock")) {
+ dirtyCodeBlocks.add(child);
+ } else if (child.childCount > 0) {
+ lookForCodeBlocks(child);
+ }
+ }
+ }
+
for (const change of changes) {
dbg("change " + JSON.stringify(change));
- if (change.type == "insert" && change.name == "codeBlock") {
+ if (change.name !== "paragraph" && change.name !== "codeBlock" && change.position.nodeAfter?.childCount > 0) {
+ /*
+ * We need to look for code blocks recursively, as they can be placed within a <div> due to
+ * general HTML support or normally underneath other elements such as tables, blockquotes, etc.
+ */
+ lookForCodeBlocks(change.position.nodeAfter);
+ } else if (change.type == "insert" && change.name == "codeBlock") {
// A new code block was inserted
const codeBlock = change.position.nodeAfter;
// Even if it's a new codeblock, it needs dirtying in case